2015-04-14 59 views
0

我試圖導入Excel文件,我的邏輯做的是正確的:C# - 導入Excel文件,而無需知道表名稱

private void SaveFileToDB(UploadedFile uploadedFile) 
{ 
     string path = Server.MapPath("uploads/" + uploadedFile.FileName); 


     int currentContractId = Convert.ToInt32(Session["id"]); 

     string connnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"; 
     OleDbConnection con = new OleDbConnection(connnection); 
     OleDbCommand command = new OleDbCommand(); 

     DataTable dt = new DataTable(); 
     OleDbDataAdapter myCommand = new OleDbDataAdapter(**"select * from [Sheet1$]"**, con); 

     myCommand.Fill(dt); 
     int count = 0; 
     //some code... 

} 

正如你所看到的,我硬編碼的名稱我的命令中的Excel工作表,我想知道如何繼續使其動態。

回答

0

那麼,一種方法是找到所有的表。

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open("D:\\Book1.xlsx"); 

String[] excelSheets = new String[excelBook.Worksheets.Count]; 
    int i = 0; 
    foreach(Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)  
    { 
     excelSheets[i] = wSheet.Name; 
     i++; 
    } 

來源:Excel Sheet Names in Sheet Order

1

如果你正在尋找避免使用互操作,並希望只使用OLEDB,你可以使用下面來獲取工作表名稱:

var sheetNames = con.GetSchema("Tables"); 
foreach (DataRow row in sheetNames.Rows) 
{ 
    var name = row["TABLE_NAME"]; 
    //select from this sheet 
    //do whatever else 
} 
相關問題