如何使用 vb.net 或 c# 从 excel 2007 (*.xlsx) 中获取工作表名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13618224/
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-08-10 09:12:20  来源:igfitidea点击:

how to get sheets name from excel 2007 (*.xlsx) using vb.net or c#

c#vb.netexcel-2007

提问by Fauzi88

I try to get sheets name from file excel using vb.net and show them into textbox. I was try with this code:

我尝试使用 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

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. error message

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

What should I do? Can you help me please.

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

采纳答案by JokoSumanto

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

回答by Thomas C

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/

回答by Jayant Varshney

try using

尝试使用

For Each ews In ewb.Sheets
   ExcelSheetName += ews.Name & vbNewLine
Next ews