C# - 在不知道工作表名称的情况下导入Excel文件

时间:2015-04-14 12:03:39

标签: c# oledb import-from-excel oledbcommand

我正在尝试导入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工作表的名称,我想知道如何使其动态化。

2 个答案:

答案 0 :(得分:1)

如果您希望避免使用Interop并且只想使用oledb,则可以使用以下内容获取工作表名称:

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

答案 1 :(得分: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