如何使用OleDbConnection类(或其他任何东西)读取XLS文件?

时间:2013-05-03 15:39:40

标签: c# io oledbconnection

private void readXLSData()
    {
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\nsharifzadeh\\Desktop\\Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""");
        con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
    }

我使用了调试器,它似乎一直工作到da.Fill(ds)然后它炸弹说:

*The Microsoft Jet database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.*

我发誓Sheet的名字是Sheet1!我在这里做错了吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以尝试一件事,有时候工作表名称需要''围绕它...就像'Sheeet1 $'

OleDbDataAdapter da = new OleDbDataAdapter("select * from ['Sheet1$']", con);

如果那不起作用。在你的连接上尝试这个。

DataTable schemaTable = con.GetSchema("TABLES");
foreach (DataRow dataRow in con.Rows)
{
    //tablename = rowData[2]  check those contents to see the sheet names in the excel spreadsheet.
}

现在我一直在使用Excel 12.0和Microsoft.ACE.OLEDB.12.0,但这不应该重要