From Excel to DataTable in C# with Open XML

前端 未结 7 2046
暖寄归人
暖寄归人 2020-11-29 00:29

I\'m using Visual Studio 2008 and I need create a DataTable from a Excel Sheet using the Open XML SDK 2.0. I need to create it with the DataTable columns with t

相关标签:
7条回答
  • 2020-11-29 01:12
     Public Shared Function ExcelToDataTable(filename As String) As DataTable
            Try
    
                Dim dt As New DataTable()
    
                Using doc As SpreadsheetDocument = SpreadsheetDocument.Open(filename, False)
    
                    Dim workbookPart As WorkbookPart = doc.WorkbookPart
                    Dim sheets As IEnumerable(Of Sheet) = doc.WorkbookPart.Workbook.GetFirstChild(Of Sheets)().Elements(Of Sheet)()
                    Dim relationshipId As String = sheets.First().Id.Value
                    Dim worksheetPart As WorksheetPart = DirectCast(doc.WorkbookPart.GetPartById(relationshipId), WorksheetPart)
                    Dim workSheet As Worksheet = worksheetPart.Worksheet
                    Dim sheetData As SheetData = workSheet.GetFirstChild(Of SheetData)()
                    Dim rows As IEnumerable(Of Row) = sheetData.Descendants(Of Row)()
    
                    For Each cell As Cell In rows.ElementAt(0)
                        dt.Columns.Add(GetCellValue(doc, cell))
                    Next
    
                    For Each row As Row In rows
                        'this will also include your header row...
                        Dim tempRow As DataRow = dt.NewRow()
    
                        For i As Integer = 0 To row.Descendants(Of Cell)().Count() - 1
                            tempRow(i) = GetCellValue(doc, row.Descendants(Of Cell)().ElementAt(i))
                        Next
    
                        dt.Rows.Add(tempRow)
                    Next
                End Using
    
                dt.Rows.RemoveAt(0)
    
                Return dt
    
            Catch ex As Exception
                Throw ex
            End Try
        End Function
    
    
        Public Shared Function GetCellValue(document As SpreadsheetDocument, cell As Cell) As String
            Try
    
                If IsNothing(cell.CellValue) Then
                    Return ""
                End If
    
                Dim value As String = cell.CellValue.InnerXml
    
                If cell.DataType IsNot Nothing AndAlso cell.DataType.Value = CellValues.SharedString Then
                    Dim stringTablePart As SharedStringTablePart = document.WorkbookPart.SharedStringTablePart
                    Return stringTablePart.SharedStringTable.ChildElements(Int32.Parse(value)).InnerText
                Else
                    Return value
                End If
    
            Catch ex As Exception
                Return ""
            End Try
        End Function
    
    0 讨论(0)
提交回复
热议问题