2016-08-04 108 views
3

我新的C#和我想讀一個Excel用下面的代碼閱讀Excel文件C#

string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + 
       ";Extended Properties=Excel 12.0;"; 
using (OleDbConnection connection = new OleDbConnection(conStr)) 
{ 
    connection.Open(); 
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using (OleDbDataReader dr = command.ExecuteReader()) 
    { 
     while (dr.Read()) 
     { 
      var row1Col0 = dr[0]; 
      Console.WriteLine(row1Col0); 
     } 
    } 
} 

我收到以下錯誤文件:

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

誰能告訴我我做錯了什麼?

Excel工作表的名稱是sheet.xlsx

enter image description here 感謝

+2

這是該文件的名稱。文件中標籤上的名稱是什麼? IIRC這是牀單。 – CaffGeek

+0

我附上excel表格的圖片 – wearybands

+0

表格底部的標籤名稱是什麼。 – CaffGeek

回答

3

的工作表名稱可能不是相同的文件名,你可以通過執行獲得第一個工作表名稱下面

首先,獲取架構

DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

然後得到第一張名

var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString(); 

你得到command後,您就可以填充DataSet和工作與它的.Rows收集

var myDataSet = new DataSet(); 
command.Fill(myDataSet); 

的SHEETNAME是這個 enter image description here

+0

我可以逐行讀取表格嗎? – wearybands

+0

我會用'command.Fill'將數據放入數據集中,然後像數據集一樣正常工作 – CaffGeek

+0

您可以提供一些psudocode我非常新的C# – wearybands