我尝试使用vb.net从文件excel中获取工作表名称并将其显示到文本框中。我试过这段代码:
Imports Microsoft.Office.Interop
Private Sub GetSheetsName
Dim efa As New Excel.Application
Dim ewb As Excel.Workbook
Dim ews As Excel.Worksheet
Dim fileName as string
fileName="D:\test.xls"
ewb = efa.Workbooks.Open(fileName)
For Each ews In ewb.Worksheets
ExcelSheetName += ews.Name & vbNewLine
Next ews
TextBox1.text=ExcelSheetName
end sub
该代码适用于文件excel * .xls,在文本框中显示Sheets Name from file test.xls
Sheet1
Sheet2
Sheet3
但是当我尝试使用excel 2007(* .xlsx)时,会显示如下错误消息。
我该怎么办?你能帮我吗?
答案 0 :(得分:10)
试试这段代码:
Private Sub GetExcelSheetNames(ByVal fileName As String)
Dim strconn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &
fileName & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Dim conn As New OleDbConnection(strconn)
conn.Open()
Dim dtSheets As DataTable =
conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
//show sheetname in textbox where multiline is true
For Each sheet As String In listSheet
TextBox1.Text = TextBox1.Text & sheet & vbNewLine
Next
conn.Close()
End Sub
答案 1 :(得分:0)
处理xlsx文件的优秀库是EPPlus。
这是一个示例代码:
var existingFile = new FileInfo(path);
var sheets = new List<string>();
using (var package = new ExcelPackage(existingFile))
{
sheets.AddRange(from worksheet in package.Workbook.Worksheets where worksheet.Dimension != null select worksheet.Name);
}
你可以在这里找到它:http://epplus.codeplex.com/
答案 2 :(得分:0)
尝试使用
For Each ews In ewb.Sheets
ExcelSheetName += ews.Name & vbNewLine
Next ews