簡體   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