How to get sheetname of the uploaded excel file using C#?
Asked Answered
I

4

7

I would like to get the sheet name of the uploaded excel file using C# code. The file may be in .xls or .xlsx format. The Code I have used is as follows:

protected void btnGenerateCSV_Click(object sender, EventArgs e)
{            
    string sourceFile = ExcelFileUpload.PostedFile.FileName;
    string worksheetName = ?? //(How to get the first sheetname of the uploaded file)                
    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";

    if (sourceFile.Contains(".xlsx"))
    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";

    try
    {
        conn = new OleDbConnection(strConn);
        conn.Open();

        cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
        cmd.CommandType = CommandType.Text;
        wrtr = new StreamWriter(targetFile);

        da = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        for (int x = 0; x < dt.Rows.Count; x++)
            {
                string rowString = "";
                for (int y = 0; y < dt.Columns.Count; y++)
                {
                    rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
                }
                wrtr.WriteLine(rowString);
            }
    }
    catch (Exception exp)
    {
    }
    finally
    {
        if (conn.State == ConnectionState.Open)
        conn.Close();
        conn.Dispose();
        cmd.Dispose();
        da.Dispose();
        wrtr.Close();
        wrtr.Dispose();
    }
}
  • (How to get the first sheetname of the uploaded file) string worksheetName = ??
Izanami answered 28/6, 2013 at 6:46 Comment(0)
D
7

I use this to get sheet names from a .xlsx file and loop through all the names to read sheets one by one.

OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0 xml;HDR=YES;'");
connection.Open();
DataTable Sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

foreach(DataRow dr in Sheets.Rows)
{
    string sht = dr[2].ToString().Replace("'", "");
    OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + sht + "]", connection);
}
Diaphaneity answered 28/6, 2013 at 6:49 Comment(10)
Thanks for your reply but I am just getting an empty string. Please help out.Izanami
@prabuR is the datatable sheets empty? can you show the code that you triedDiaphaneity
conn = new OleDbConnection(strConn); conn.Open(); DataTable Sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); foreach (DataRow dr in Sheets.Rows) { worksheetName = dr[0].ToString(); } cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);Izanami
Excel file I have uploaded is having 1 sheetIzanami
is DataTable Sheets empty?Diaphaneity
use worksheetName = dr[2].ToString(); here 2 specifies the position of columnDiaphaneity
It works. Thanks. Is there any way to give the sheetname of the generated file similar to the uploaded file's sheetname?Izanami
how do you generate the file ? using interop?Diaphaneity
No. I have updated the question with the complete code I have used.Izanami
i dont think you can..seems you are appending string ..try if its possible through an interopDiaphaneity
B
2
DataTable Sheets = oleConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

for(int i=0;i<Sheets.Rows.Count;i++)
{
   string worksheets= Sheets.Rows[i]["TABLE_NAME"].ToString();
   string sqlQuery = String.Format("SELECT * FROM [{0}]", worksheets);
}
Barbi answered 5/1, 2014 at 7:19 Comment(2)
Please add some commentary as to what is going on here.Tola
the code fetches excel schema into datatable and iterates over to find the sheetnames. karthik as used integer index to access sheet name and i have used the column name["TABLE_NAME"] which is more preciseBarbi
C
0

If the Excel is too big, This code will waste a lot of time in(conn.open()). Use Openxml will be better(use less time),but if the Excel is Open---Using openxml to read will have the exception but oldbhelper wile have no exception. My english is pool , sorry.-----Chinese boy

Contreras answered 29/9, 2014 at 9:12 Comment(1)
Could you provide the code on how to do it, please?Rosenzweig
A
0

I use Microsoft excel library Microsoft.Office.Interop.Excel. Then you can use index to get the worksheet name as following.

        string path = @"C\Desktop\MyExcel.xlsx" //Path for excel
        using Excel = Microsoft.Office.Interop.Excel;
        xlAPP = new Excel.Application();
        xlAPP.Visible = false;
        xlWbk = xlAPP.Workbooks.Open(path);
        string worksheetName = xlWbk.Worksheets.get_Item(1).Name //pass Index here. Reemember that index starts from 1.
        xlAPP.Quit();
        releaseObject(xlWbk);
        releaseObject(xlAPP);

    //Always handle unmanaged code.
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }
Appoggiatura answered 27/7, 2015 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.