3

我尝试使用 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,在文本框中显示文件 test.xls 中的表格名称

Sheet1
Sheet2
Sheet3

但是当我尝试使用 excel 2007 (*.xlsx) 时,会显示这样的错误消息。 错误信息

我应该怎么办?你能帮我吗。

4

3 回答 3

11

试试这个代码:

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
于 2012-12-03T05:48:56.710 回答
0

尝试使用

For Each ews In ewb.Sheets
   ExcelSheetName += ews.Name & vbNewLine
Next ews
于 2012-11-29T04:46:17.700 回答
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/

于 2012-11-29T04:12:19.300 回答