Read a single cell from Excel to a string using C# and ASP.NET

烂漫一生 提交于 2021-02-11 16:16:39

问题


I need to read a single cell from an xsl excel file to a string withing the web application i am building. I was previously pulling cell ranges from the file to a table using the following code:

string PullFromExcell(string CellNo)
    {
        string cell;
        string properties = String.Format(@"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\User\Desktop\file.xls; Extended Properties = 'Excel 8.0;'");

        using (OleDbConnection conn = new OleDbConnection(properties))
        {
            string worksheet = "Sheet";
            conn.Open();
            DataSet ds = new DataSet();
            using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + worksheet + "$" + CellNo + "]", properties))
            {

                DataTable dt = new DataTable();
                cell = dt.ToString(); 
                da.Fill(dt);
                ds.Tables.Add(dt);

                grdComponent.DataSource = dt;
                grdComponent.DataBind();
            }
        }

       return cell;
    }

How would i send that to a string? The code that i would use when pulling from a database is similar to this:

Sqlstring = "Select data from variable where name = 'fred' and ssn = 1234";
var cmd0 = new SqlCommand(Sqlstring, Class_Connection.cnn);
string Data = cmd0.ExecuteScalar().ToString();

i'm just not sure if any of that is compatible.


回答1:


After filling DataTable, you can search the row like this:

foreach (DataRow dr in dt.Rows)
{
    if (dr["name"] == "fred" && dr["ssn"] == "1234")
    {
        cell = dr["data"].ToString();
        break;
    }
}


来源:https://stackoverflow.com/questions/52172574/read-a-single-cell-from-excel-to-a-string-using-c-sharp-and-asp-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!