使用C#和ASP.NET将Excel中的单个单元格读取为字符串 [英] Read a single cell from Excel to a string using C# and ASP.NET

查看:58
本文介绍了使用C#和ASP.NET将Excel中的单个单元格读取为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将xsl excel文件中的单个单元格与正在构建的Web应用程序一起读取为字符串.我以前使用以下代码将单元格范围从文件拉到表中:

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.

推荐答案

填充DataTable之后,您可以像这样搜索行:

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;
    }
}

这篇关于使用C#和ASP.NET将Excel中的单个单元格读取为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆