如何使用C#获取上传的excel文件的工作表名称?

时间:2013-06-28 06:46:51

标签: c# .net excel file-upload oledb

我想使用C#代码获取上传的excel文件的工作表名称。该文件可能是.xls或.xlsx格式。我使用的代码如下:

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

string worksheetName = ???(如何获取上传文件的第一个表名)

任何人请帮忙......

4 个答案:

答案 0 :(得分:5)

我使用它从.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);
    }

答案 1 :(得分:1)

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

答案 2 :(得分:0)

如果Excel太大,此代码将浪费大量时间(conn.open())。使用Openxml会更好(使用更少的时间),但如果Excel是Open - 使用openxml读取将有异常,但oldbhelper wile也没有例外。我的英语是游泳池,对不起.-----中国男孩

答案 3 :(得分:0)

我使用Microsoft excel库Microsoft.Office.Interop.Excel。然后,您可以使用index来获取工作表名称。

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