繁体   English   中英

无法使用OLEDB驱动程序读取Excel工作表

[英]Unable to read Excel worksheet with OLEDB driver

我有一个带有一个工作表的excel文件。 我正在使用MicroSoft.Office.Interop.Excel读取此文件,然后执行进一步的执行。

这是我的代码:

 connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;";
               conn = new OleDbConnection(connString);
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                System.Data.DataTable dt = null;
                dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

但是,工作表不在数据表对象中。

你在哪里提到过表(WorkSheet)的名字?

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

//Get the First Sheet Name
        string firstSheetName = schemaTable.Rows[0][2].ToString(); 

        //Query String 
        string sql = string.Format("SELECT * FROM [{0}],firstSheetName); 

请参阅MSDN

如果你想玩游戏,请参阅从C#读取Excel文件

OleDbConnection oconn = new OleDbConnection(@“Provider = Microsoft.ACE.OLEDB.12.0; Data Source =”+ fileName +“; Extended Properties = Excel 12.0;”);

        //After connecting to the Excel sheet here we are selecting the data 
        //using select statement from the Excel sheet
        oconn.Open();
        DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (dbSchema == null || dbSchema.Rows.Count < 1)
        {
            throw new Exception("Error: Could not determine the name of the first worksheet.");
        }
        string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();

        string tbstrat = "M1000";
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = oconn;
        cmd.CommandText = "select * from [" + firstSheetName + "B8:" + tbstrat + "]";
        OleDbDataAdapter adap = new OleDbDataAdapter();
        DataTable dt = new DataTable();
        adap.SelectCommand = cmd;
        adap.Fill(dt);
        oconn.Close();

即使你可以试试这个

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "NameHere");

DataTable data = ds.Tables["NameHere"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM