从Excel获取工作表名称

问题描述:

我正在将excel文件上传到SQL Server数据库.我目前正在使用此行从工作表中获取数据:

I am uploading excel files to a SQL Server database. I am currently using this line to get the data from the sheet:

string myQuery = "Select * from [Sheet1$]";

问题是,如果工作表名称不是 Sheet1 ,则它将失败.有没有一种方法可以获取工作表名称,而不是在 Sheet1 中进行硬编码?

The problem is, if the sheet name isn't Sheet1 then it will fail. Is there a way to get the sheet name rather than hard coding in Sheet1?

您可以先使用

You can query the schema first using GetOleDbSchemaTable:

DataTable schemaTable = connection.GetOleDbSchemaTable(
    OleDbSchemaGuid.Tables,
    new object[] { null, null, null, "TABLE" });

第一个表的名称应为 schemaTable.Rows [0] [0] .