簡體   English   中英

獲取 Excel 工作表名稱到 C#

[英]Get Excel Worksheets Name to C#

我正在制作和從 Excel 工作簿中讀取數據的應用程序,如下所示:

excel 包含有關工程量清單 (BOQ) 的數據,其中我有大約 4 或 5 列包含數據,但 BOQ 表中有一些部門,其中有土木、建築、機械、電氣等。每一個除法在單獨的工作表中。

我的應用程序有一個 DataGridView 和一個組合框,一旦從組合框中選擇了一個部門,該組合框將被工作表(部門)的名稱填充,DataGridView 將通過該部門中的數據重新生成。

我已經編寫了一個代碼,將數據放在 DataGridView 的特定工作表中

private void button1_Click(object sender, EventArgs e)
    {
        String name = "FF";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                        "Data Source=C:\\Book1.xlsx;" + 
                        "Extended Properties='Excel 12.0 XML;" +
                        "HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oConn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oConn);
        DataTable data = new DataTable();
        sda.Fill(data);

        dataGridView1.DataSource = data;
        dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
        {
            dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
        }


    }

但我無法用工作表名稱填充組合框項目。

編輯

按照建議使用此代碼:

DataTable schemaTable = connection.GetOleDbSchemaTable(
    OleDbSchemaGuid.Tables,
    new object[] { null, null, null, "TABLE" });

返回不明確的值,如下圖所示:

[組合框結果[2]

在excel中,它們看起來像這樣:

[[1]

我的結果是使用此代碼:

    private void Form1_Load(object sender, EventArgs e)
    {

        foreach (string s in GetExcelSheetNames("C:\\Book1.xlsx"))
        {
            cboSheetName.Items.Add(s);
        }
    }

    /// <summary>
    /// This method retrieves the excel sheet names from 
    /// an excel workbook.
    /// </summary>
    /// <param name="excelFile">The excel file.</param>
    /// <returns>String[]</returns>
    private String[] GetExcelSheetNames(string excelFile)
    {
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;

        try
        {
            // Connection String. Change the excel file to the file you will search.
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                                "Data Source=" + excelFile + ";" +
                                "Extended Properties='Excel 12.0 XML;" +
                                "HDR=YES;';";

            // Create connection object by using the preceding connection string.
            objConn = new OleDbConnection(connString);

            // Open connection with the database.
            objConn.Open();

            // Get the data table containg the schema guid.
            //dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            if (dt == null)
            {
                return null;
            }

            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;

            // Add the sheet name to the string array.
            foreach (DataRow row in dt.Rows)
            {
                excelSheets[i] = row["TABLE_NAME"].ToString();
                i++;
            }

            // Loop through all of the sheets if you want too...
            for (int j = 0; j < excelSheets.Length; j++)
            {
                // Query each excel sheet.
            }

            return excelSheets;
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            // Clean up.
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }
    }

為什么不使用 Com 對象?

所以這是我在excel中獲取工作表名稱的方法:

List<string> workSheets = new List<string>();

if(xlsApp==null)
   xlsApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

Workbook book = xlsApp.Workbooks.Open(file.FullName, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
foreach (Worksheet sheet in book.Worksheets)
{
    workSheets.Add(sheet.Name);
}
xlsApp.Workbooks.Close();
xlsApp.Quit();

顯然,您只需要過濾$結尾的名稱,它們將始終按字母順序排列:

var sheetNames = cn.GetSchema("TABLES").AsEnumerable()
                   .Select(r => r.Field<string>("TABLE_NAME"))
                   .Where(n => n.EndsWith("$'"))
                   .Select(n => n.Substring(1, n.Length-3))
                   .ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM