简体   繁体   English

如何使用C#获取上传的excel文件的sheetname?

[英]How to get sheetname of the uploaded excel file using C#?

I would like to get the sheet name of the uploaded excel file using C# code.我想使用C#代码获取上传的 excel 文件的工作表名称。 The file may be in .xls or .xlsx format.该文件可能是.xls.xlsx格式。 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 = ?? (如何获取上传文件的第一个sheetname ) string worksheetName = ??

I use this to get sheet names from a .xlsx file and loop through all the names to read sheets one by one.我使用它从.xlsx文件中获取工作表名称并遍历所有名称以一张一张地读取工作表。

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

If the Excel is too big, This code will waste a lot of time in(conn.open()).如果Excel太大,这段代码会在(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.使用Openxml会更好(使用更少的时间),但如果Excel是Open的---使用openxml读取会有异常但oldbhelper wile没有异常。 My english is pool , sorry.-----Chinese boy我的英语是游泳池,对不起。-----中国男孩

I use Microsoft excel library Microsoft.Office.Interop.Excel.我使用 Microsoft excel 库 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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用工作表名称获取我的Excel文件的FilePath - Get FilePath for my excel file with sheetname 在C#中读取具有多个工作表的Excel的Excel工作表名称 - To read excel sheetname for Excel having multiple sheet in C# 如何获取用户 C# 上传的文件的 contentByte - How to get the contentByte for the file that is uploaded by user C# 使用c#将文件上传到DailyMotion后,如何“创建视频” - How to “create the video” after file uploaded to DailyMotion using c# 如何在MVC控制器中上传Excel文件 - How to get an excel file uploaded in MVC controller 如何使用 C# 导出 Excel 文件 - How to Export an Excel File using C# 如何使用带有 Interop.Excel 库的 C# 从现有 Excel 文件中获取特定元素? - How to get specific elements from an existing Excel file using C# with the Interop.Excel library? 从上传的Excel文件在Gridview表C#中插入超链接 - Insert hyperlinks in Gridview table c# from uploaded excel file 如何使用OLEDB连接上传的Excel文件? - How connect the uploaded excel file using OLEDB? C#-将上传的Excel文件保存到MemoryStream,然后使用它填充DataTable - C# - Save uploaded Excel file to MemoryStream, then use it to fill a DataTable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM