我是 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
最佳答案
工作表名称可能与文件名不同,您可以通过执行以下操作获取第一个工作表名称
首先,获取模式
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
然后获取第一个工作表名称
var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
获得命令
后,您可以填充数据集并使用它的.Rows
集合
var myDataSet = new DataSet();
command.Fill(myDataSet);
关于c# - 使用C#读取Excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38770574/