Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the name of the first page of an excel workbook?

Tags:

c#

excel

Suppose you don't know the name of the first worksheet in an excel workbook. And you want to find a way to read from the first page. This snippet sometimes works, but not always. Is it just me? Or is there a no brainer way to do this?

            MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + inputFile + "';Extended Properties=Excel 8.0;");

            String[] excelSheets = new String[tbl.Rows.Count]; 
            int i = 0;
            foreach (DataRow row in tbl.Rows)
            {
                excelSheets[i] = row["TABLE_NAME"].ToString();
                i++;
            }
            string pageName = excelSheets[0]; 

            OleDbDataAdapter myAdapter = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" + pageName + "]", MyConnection);

Note: I am looking for the name of the first worksheet.

like image 726
eviljack Avatar asked Dec 13 '22 02:12

eviljack


1 Answers

If you have Office installed on the machine, why not just use Visual Studio Tools for Office (VSTO). Here is essentially the code to get the worksheet:

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook =  app.Workbooks.Open(fileName,otherarguments);
Microsoft.Office.Interop.Excel.Worksheet worksheet =  workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
like image 182
Jacob Adams Avatar answered Dec 16 '22 18:12

Jacob Adams