简体   繁体   中英

C# - Importing Excel file without knowing the sheet name

I'm trying to import an Excel file and my logic to do that is correct :

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...

}

As you can see, I'm hardcoding the name of the Excel Sheet in my command and I wanted to know how to proceed to make it dynamic.

If you're looking to avoid using Interop and want to just use oledb, you can use the below to get the sheet names:

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

Well, one way is just to find all sheets.

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++;
    }

Source: Excel Sheet Names in Sheet Order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM