Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear ,

i am importing 1 excel file into my database.

I need to read its sheet name for below statement

command.CommandText = "SELECT * FROM [Sheet1$]";


But it is not case where always first excel sheet name is not "Sheet1".

I want to reas first excel sheet name. Please guide me.

Thank you
Posted
Updated 2-May-11 21:03pm
v2
Comments
Ankit Rajput 3-May-11 3:03am    
EDIT: Code block added

Hi,

Please go through with this article. It might help you
C# - Retrieve Excel Workbook Sheet Names.

Regards AR
 
Share this answer
 
u can do like this

C#
DataTable dtExcelsheetname = new DataTable();
       excelcon.Open();
       dtExcelsheetname = excelcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
       string[] excelSheets = new String[dtExcelsheetname.Rows.Count];
       int j = 0;
       foreach (DataRow row in dtExcelsheetname.Rows)
       {
           excelSheets[j] = row["TABLE_NAME"].ToString();
           j++;
       }
       excelcon.Close();
       string strquery = "select * from [" + excelSheets[0].ToString() + "]";


hope it helps
 
Share this answer
 
you can use given method to get all the sheetnames from an excel file using oledb

public string[] GetSheetNamesForExcel(string filename)
        {
            System.Data.DataTable dt = GetDataTable(filename, OleDbSchemaGuid.Tables);
            String[] excelSheets = null;
            try
            {
                if (dt != null)
                {
                    excelSheets = new String[dt.Rows.Count];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow row = dt.Rows[i];

                        string name = row["TABLE_NAME"].ToString();
                        name = name.Replace("'", String.Empty);
                        name = name.Replace("$", String.Empty);
                        excelSheets[i] = name;
                    }
                    dt.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return excelSheets;
        }
 
Share this answer
 
Comments
Vivek Deshmukh 3-May-11 5:00am    
Thanks sir,
I do the same it works

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900