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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38114793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:58:35  来源:igfitidea点击:

How To Extract Excel Sheet Name From Workbook Using VB.NET?

vb.netexcel

提问by Leprechaun

I am working on payroll to import attendance of employees. Here's my code to import the excel sheet.

我正在处理工资单以导入员工的出勤率。这是我导入excel表的代码。

 Dim MyConnection As OleDbConnection = Nothing

 Dim DtSet As System.Data.DataSet = Nothing

 Dim MyCommand As OleDbDataAdapter = Nothing
 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

The problem is I want to have the sheet name dynamic From "[Sheet1$]"to any name. I am new to this concept so find it tough to find the relevant solution.

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

Thanks in advance.

提前致谢。

回答by Leprechaun

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

Your strSheetName string has the name of the sheet which you can pass. If you have more than one sheet and want all the data from them then

您的 strSheetName 字符串具有您可以传递的工作表的名称。如果您有不止一张纸并且想要其中的所有数据,那么

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