如何使用VB.NET从工作簿中提取Excel工作表名称?

时间:2016-06-30 05:42:11

标签: vb.net excel

我正在编制工资单以输入员工的出勤率。这是导入Excel工作表的代码。

 Dim MyConnection As OleDbConnection = Nothing

 Dim DtSet As System.Data.DataSet = Nothing

 Dim MyCommand As OleDbDataAdapter = Nothing
    With OpenFileDialog1
        .Filter = "Excel files(*.xlsx)|*.xlsx|Excel (97-2003) files(*.xls)|*.xls|All files (*.*)|*.*"
        .FilterIndex = 1
        .Title = "Import data from Excel file"
    End With
    If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
        Dim fname As String
        fname = OpenFileDialog1.FileName
        MyConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & fname & " '; " & "Extended Properties=Excel 8.0;")
        MyCommand = New OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
        MyCommand.TableMappings.Add("Table", "Test")
        DtSet = New System.Data.DataSet
        MyCommand.Fill(DtSet)
        ResultGrid.DataSource = DtSet.Tables(0)
        MyConnection.Close()
    End If

问题是我希望工作表名称动态从"[Sheet1$]"到任何名称。我是这个概念的新手,所以很难找到相关的解决方案。

提前致谢。

1 个答案:

答案 0 :(得分:5)

Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xlApp As New Microsoft.Office.Interop.Excel.Application

xlApp.Workbooks.Open(fname, 0, True)

' For the first sheet in an excel spreadsheet
xlWorkSheet = CType(xlApp.Sheets(1), _
                    Microsoft.Office.Interop.Excel.Worksheet)
Dim strSheetName as String = xlSheetName.Name

您的strSheetName字符串具有您可以传递的工作表的名称。 如果您有多张工作表并希望获得所有数据,那么

Dim strSheetName as New List(of String)
For each xlWorkSheet in xlApp.Sheets
    strSheetName.Add(xlWorkSheet.Name)
Next