vb.net数据表到EXCEL

时间:2017-01-04 01:23:09

标签: excel vb.net

出于某种原因,当我将我的数据表写入excel时,我收到以下错误消息。似乎错误发生在我的第二个for循环中。

HRESULT的异常:0x800A03EC

Public Shared Sub ExportExcel(ByVal dt As DataTable)

    Try

        Dim strFile As String = MYFilelocation
        Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
        Dim wBook As Microsoft.Office.Interop.Excel.Workbook
        Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

        wBook = excel.Workbooks.Add()
        wSheet = wBook.ActiveSheet()

        Dim dc As System.Data.DataColumn
        Dim dr As System.Data.DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0

        For Each dc In dt.Columns
            colIndex = colIndex + 1
            excel.Cells(1, colIndex) = dc.ColumnName
        Next

        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
                excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
            Next
        Next

        wSheet.Columns.AutoFit()
        wBook.SaveAs(strFile)
        wBook.Close()

    Catch ex As Exception
        MessageBox.Show("there was an issue Exporting to Excel" & ex.ToString)
    End Try


End Sub

1 个答案:

答案 0 :(得分:1)

尝试一下:

    Dim workbook = New ExcelFile
    Dim worksheet = workbook.Worksheets.Add("DataTable to Sheet")

    Dim dataTable = New DataTable

    dataTable.Columns.Add("ID", Type.GetType("System.Int32"))
    dataTable.Columns.Add("FirstName", Type.GetType("System.String"))
    dataTable.Columns.Add("LastName", Type.GetType("System.String"))

    dataTable.Rows.Add(New Object() {100, "John", "Doe"})
    dataTable.Rows.Add(New Object() {101, "Fred", "Nurk"})
    dataTable.Rows.Add(New Object() {103, "Hans", "Meier"})
    dataTable.Rows.Add(New Object() {104, "Ivan", "Horvat"})
    dataTable.Rows.Add(New Object() {105, "Jean", "Dupont"})
    dataTable.Rows.Add(New Object() {106, "Mario", "Rossi"})

    worksheet.Cells(0, 0).Value = "DataTable insert example:"

    ' Insert DataTable to an Excel worksheet.
    worksheet.InsertDataTable(dataTable,
        New InsertDataTableOptions() With
        {
            .ColumnHeaders = True,
            .StartRow = 2
        })

    workbook.Save("DataTable to Sheet.xlsx")