Traffy
Traffy

Reputation: 2861

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.

Upvotes: 1

Views: 2766

Answers (2)

mjk5182
mjk5182

Reputation: 63

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
}

Upvotes: 2

Taurib
Taurib

Reputation: 461

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

Upvotes: 0

Related Questions