[英]how to get sheets name from excel 2007 (*.xlsx) using vb.net or c#
I try to get sheets name from file excel using vb.net and show them into textbox. 我尝试使用vb.net从文件excel中获取工作表名称并将其显示到文本框中。 I was try with this code: 我试过这个代码:
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
That code was work for file excel *.xls, in textbox show Sheets Name from file test.xls 该代码适用于文件excel * .xls,在文本框中显示来自文件test.xls的Sheets Name
Sheet1
Sheet2
Sheet3
But when I try with excel 2007 (*.xlsx), then show an error message like this. 但是当我尝试使用excel 2007(* .xlsx)时,会显示如下错误消息。
What should I do? 我该怎么办? Can you help me please. 你能帮我吗。
Try this code: 试试这段代码:
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
An excellent library to handle xlsx files is EPPlus. 处理xlsx文件的优秀库是EPPlus。
here is a sample code: 这是一个示例代码:
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);
}
you can find it here: http://epplus.codeplex.com/ 你可以在这里找到它: http : //epplus.codeplex.com/
try using 尝试使用
For Each ews In ewb.Sheets
ExcelSheetName += ews.Name & vbNewLine
Next ews
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.