0

我有一个带有一个工作表的 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);

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

4

3 回答 3

2

您在哪里提到了表(工作表)名称?

    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 文件

于 2012-12-21T07:27:27.083 回答
0

即使你可以试试这个

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

adapter.Fill(ds, "NameHere");

DataTable data = ds.Tables["NameHere"];
于 2012-12-21T11:08:49.700 回答
0

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();
于 2012-12-21T10:33:28.437 回答