2016-06-30 55 views
0

我正在工资单上导入员工出勤率。这是我的代码来导入Excel表。如何从使用VB.NET的工作簿中提取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$]"任何名称。我对这个概念很陌生,因此很难找到相关的解决方案。

在此先感谢。

+0

您可以使用一个文本框,在其中输入表名称,那么你的命令,切换到这样的事情: 'mycommand的=新OleDbDataAdapter(“select * from [”&txtSheetName.text&“$”“,MyConnection)' – HaPhan

回答

2
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 
相关问题