c# - 使用C#读取Excel文件

标签 c# excel

我是 C# 的新手,我正在尝试使用以下代码读取 excel 文件

string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + 
                ";Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(conStr))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
    using (OleDbDataReader dr = command.ExecuteReader())
    {
        while (dr.Read())
        {
            var row1Col0 = dr[0];
            Console.WriteLine(row1Col0);
        }
    }
}

我收到以下错误:

Sheet1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.

谁能告诉我我做错了什么?

excel表格名称为sheet.xlsx

enter image description here 谢谢

最佳答案

工作表名称可能与文件名不同,您可以通过执行以下操作获取第一个工作表名称

首先,获取模式

DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

然后获取第一个工作表名称

var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();

获得命令后,您可以填充数据集并使用它的.Rows 集合

var myDataSet = new DataSet();
command.Fill(myDataSet);

工作表名称是这个 enter image description here

关于c# - 使用C#读取Excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38770574/

相关文章:

vba - Excel VBA : Compiler Errors

c# - 在 .Net Core 中使用 app.config

c# - 将JSON反序列化为c#对象

c# - 重置重复协程延迟

excel - 在 2 个子程序之间传递值时出错

vba - Excel 公式到 excel-vba

python - 在没有安装 xlwings 的情况下分发 xlwings 宏?

c# - 如何在 C# 中为 Canvas signed_request 解码 OAuth 2.0?

c# - WPF 如何确定应该重绘某些内容?我怎么知道?

Excel Power Query - 是否可以使用 SAS 身份验证或 Azure AD 帐户连接到 Azure Blob 存储