【问题标题】:Order of sheets in Excel file while reading with GetOleDbSchemaTable使用 GetOleDbSchemaTable 读取时 Excel 文件中的工作表顺序
【发布时间】:2014-10-01 15:02:19
【问题描述】:

我正在使用下面的 ACE.OLEDB 来读取 C# 中的 excel 文件。 我的 Excel 文件具有以下表格,并按以下顺序:

Sheet1、Sheet1 (2)、Sheet2

我的代码中的变量 sheetName 将“Sheet1 (2)”作为第一个工作表,而不是“Sheet1”。

我的问题是它如何确定工作表的顺序?

string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
// Extra blank space cannot appear in Office 2007 and the last version. And we need to pay attention on semicolon.


using (OleDbConnection conn = new OleDbConnection(connstring))
{
    conn.Open();
    System.Data.DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "Table"});
    string firstSheetName = sheetsName.Rows[0][2].ToString();
    string sql = string.Format("select * from [{0}]", firstSheetName);
    OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
    DataSet set = new DataSet();
    ada.Fill(set);

【问题讨论】:

    标签: c# excel oledbconnection


    【解决方案1】:

    根据this post,版主说I am afraid that OLEDB does not preserve the sheet order as they were in Excel.

    虽然在谷歌上搜索,我发现 this SO answer 可能会对您有所帮助。

    【讨论】:

    • 感谢 icemanind 的链接。所以,如果我知道顺序,那么另一个解决方案可能是硬编码工作表名称,如 string sql = string.Format("select * from [{0}]", "Sheet1$");对吗?
    • @Nish - 是的。我自己没有尝试过,但从我读过的内容来看,这似乎是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多