如何使用 OLEDB 读取 xls 文件?

how to Read xls file using OLEDB?

我想使用 OLEDB 从 xls 文件中读取所有数据,但我没有这方面的经验。

string filename = @"C:\Users\sasa\Downloads\user-account-creation_2.xls";
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES'";

using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connString))
{
    conn.Open();
    System.Data.OleDb.OleDbCommand selectCommand = new System.Data.OleDb.OleDbCommand("select * from [Sheet1$]", conn);
    System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(selectCommand);

    DataTable dt = new DataTable();
    adapter.Fill(dt);

    int counter = 0;
    foreach (DataRow row in dt.Rows)
    {
        String dataA = row["email"].ToString();
        // String dataB= row["DataB"].ToString();
        Console.WriteLine(dataA + " = ");
        counter++;
        if (counter >= 40) break;
    }
}

我想从电子邮件行中读取所有数据

我收到这个错误

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

是否可以使用 Open XML SDK?

https://docs.microsoft.com/en-us/office/open-xml/how-to-retrieve-the-values-of-cells-in-a-spreadsheet

那么,您没有 sheet 名为 Sheet1 的是吗?您的 sheet 似乎被称为 "email address from username" 所以您的查询应该是....

Select * From ['email address from username$']

另外请不要使用 Microsoft.Jet.OLEDB.4.0,因为它现在已经过时了。使用 Microsoft.ACE.OLEDB.12.0。如果您在扩展属性中指定 Excel 12.0,它将同时打开 .xls 和 .xlsx 文件。

您也可以用一行加载 DataTable...

dt.Load(new System.Data.OleDb.OleDbCommand("Select * From ['email address from username$']", conn).ExecuteReader());

要读取文件中表的名称,请使用...

DataTable dtTablesList = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

foreach (DataRow drTable in dtTablesList.Rows)
{
    //Do Something
    //But be careful as this will also return Defined Names. i.e ranges created using the Defined Name functionality
    //Actual Sheet names end with $ or $'
    if (drTable["Table_Name"].ToString().EndsWith("$") || drTable["Table_Name"].ToString().EndsWith("$'"))
    {
        Console.WriteLine(drTable["Table_Name"]);
    }
}