VB.NET OpenXML 读取 Excel 文件

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

VB.NET OpenXML to Read Excel File

vb.netopenxmlvb.net-2010openxml-sdkxmlreader

提问by John Galt

I have been searching for a way to effectively read an Excel file and have found the following code for parsing and reading a large spreadsheet:

我一直在寻找一种有效读取 Excel 文件的方法,并找到了以下用于解析和读取大型电子表格的代码:

Public Sub ExcelProcessing()

公共子 ExcelProcessing()

    Dim strDoc As String = "C:\Documents and Settings\Practice.xlsx"
    Dim txt As String

    Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open(strDoc, False)

    Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart
    Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First()

    Dim reader As OpenXmlReader = OpenXmlReader.Create(worksheetPart)
    Dim text As String
    While reader.Read()

        If reader.ElementType = GetType(CellValue) Then


            text = reader.GetText()
            MessageBox.Show(text)

        End If


    End While

The issue is where I assign reader.GetText() to my string. The value passed is a small integer while the actual cell value is a string. The messagebox fires once for each populated cell, so this tells me the code is finding cells that contain values; however, I can not extract the actual "inner text" of the cell.

问题是我将 reader.GetText() 分配给我的字符串。传递的值是一个小整数,而实际的单元格值是一个字符串。消息框为每个填充的单元格触发一次,所以这告诉我代码正在查找包含值的单元格;但是,我无法提取单元格的实际“内部文本”。

Thoughts? Suggestions?

想法?建议?

采纳答案by John Galt

I found my answer; I need to reference the sharedstringtable and pull out the inner text from there:

我找到了答案;我需要引用 sharedstringtable 并从那里拉出内部文本:

    Dim strDoc As String = "C:\Documents and Settings\Practice.xlsx"
    Dim txt As String

    Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open(strDoc, False)

    Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart
    Dim shareStringPart As SharedStringTablePart = workbookPart.SharedStringTablePart


    For Each Item As SharedStringItem In shareStringPart.SharedStringTable.Elements(Of SharedStringItem)()

        MessageBox.Show(Item.InnerText)

    Next