微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用openxml sdk 2.0读取excel文件中的多个工作表

如何解决使用openxml sdk 2.0读取excel文件中的多个工作表

我确实在excel中从单个工作表中提取数据,但需要从excel中存储超过1个工作表的数据。但没有得到任何如何去做。 下面是代码

Protected Sub upl_excel(sender As Object,e As EventArgs) Handles btnfromexcel.Click
        'Save the uploaded Excel file.
        Dim filePath As String = Server.MapPath("./UplExcel_Files") + Path.GetFileName(c_upload.PostedFile.FileName)
        c_upload.SaveAs(filePath)

        'Open the Excel file in Read Mode using OpenXml.
        Using doc As SpreadsheetDocument = SpreadsheetDocument.Open(filePath,False)
            'Read the first Sheet from Excel file.
            Dim sheet As Sheet = doc.WorkbookPart.Workbook.Sheets.GetFirstChild(Of Sheet)()
            'Get the Worksheet instance.
            Dim worksheet As Worksheet = TryCast(doc.WorkbookPart.GetPartById(sheet.Id.Value),WorksheetPart).Worksheet
            'Fetch all the rows present in the Worksheet.
            Dim rows As IEnumerable(Of Row) = worksheet.GetFirstChild(Of SheetData)().Descendants(Of Row)()
            'Create a new DataTable.
            Dim dt1 As New DataTable()
            'Loop through the Worksheet rows.
            For Each row As Row In rows
                'Use the first row to add columns to DataTable.
                If row.RowIndex.Value = 1 Then
                    For Each cell As Cell In row.Descendants(Of Cell)()
                        dt1.Columns.Add(GetValue(doc,cell))
                    Next
                Else
                    'Add rows to DataTable.
                    dt1.Rows.Add()
                    Dim i As Integer = 0
                    For Each cell As Cell In row.Descendants(Of Cell)()
                        dt1.Rows(dt1.Rows.Count - 1)(i) = GetValue(doc,cell)
                        i += 1
                    Next
                End If
            Next
            GrdChemistry1.DataSource = dt1
            GrdChemistry1.DataBind()
            ''2nd child
            'GridView1.DataSource = dt
            'GridView1.DataBind()
        End Using
    End Sub

Private Function GetValue(doc As SpreadsheetDocument,cell As Cell) As String
        Dim value As String = cell.CellValue.InnerText
        If cell.DataType IsNot nothing AndAlso cell.DataType.Value = CellValues.SharedString Then
            Return doc.WorkbookPart.SharedStringTablePart.SharedStringTable.ChildElements.GetItem(Integer.Parse(value)).InnerText
        End If
        Return value
    End Function

如果有任何想法如何实现它,我们将不胜感激。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。