简体   繁体   中英

VB.NET OpenXML to Read Excel File

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:

Public Sub 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.

Thoughts? Suggestions?

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

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM