如何将 Datagridview 导出到 Excel 工作簿

How to Export Datagridview to Excel Workbook

我在尝试将 Datagridview 导出到 excel 工作簿时遇到了问题 运行。我有 2 个不同的代码,第一个抛出关于空值的错误,第二个将数据导出到 excel 但它缺少 headers 和一列或 2。您可以给出的任何方向都是非常感谢。

这个抛出空错误

        'Creating DataTable
        Dim dt As New DataTable()

        'Adding the Columns
        For Each column As DataGridViewColumn In DataGridView1.Columns
            dt.Columns.Add(column.HeaderText, column.ValueType)
        Next

        'Adding the Rows
        For Each row As DataGridViewRow In DataGridView1.Rows
            dt.Rows.Add()
            For Each cell As DataGridViewCell In row.Cells
                dt.Rows(dt.Rows.Count - 1)(cell.ColumnIndex) = cell.Value.ToString()
            Next
        Next

        'Exporting to Excel

        Dim folderPath As String = "C:\Users\" & UserName & "\Desktop\SkyNet Exports"
        If Not My.Computer.FileSystem.DirectoryExists(folderPath) Then
            My.Computer.FileSystem.CreateDirectory(folderPath)
        End If
        Dim wb As New Excel.Application()
        wb.Worksheets.Add(dt, "Skills")
        wb.SaveAs(folderPath & Convert.ToString("SkyNet Export.xlsx"))

并且这个导出到 excel 但缺少列并且没有 headers

    Private Sub ExportToExcel()

        Dim ExcelApp As Object, ExcelBook As Object
        Dim ExcelSheet As Object
        Dim i As Integer
        Dim j As Integer

        'create object of excel
        ExcelApp = CreateObject("Excel.Application")
        ExcelBook = ExcelApp.WorkBooks.Add
        ExcelSheet = ExcelBook.WorkSheets(1)

        With ExcelSheet
            For i = 1 To Me.DataGridView1.RowCount
                .cells(i, 1) = Me.DataGridView1.Rows(i - 1).Cells("id").Value
                For j = 1 To DataGridView1.Columns.Count - 1
                    .cells(i, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
                Next
            Next
        End With

        ExcelApp.Visible = True
        '
        ExcelSheet = Nothing
        ExcelBook = Nothing
        ExcelApp = Nothing

    End Sub

再次感谢任何帮助,我查看了不同的站点,但大多数都没有使用 VB.Net

这是第一个代码的错误 Code Error

在第二个代码中你错过了添加 headers 并且当你尝试获取列值时你用 1 启动了你的 j 迭代器所以第一列的值将丢失(如果你的 id 列不是第一个列)

Private Sub ExportToExcel()

        Dim ExcelApp As Object, ExcelBook As Object
        Dim ExcelSheet As Object
        Dim i As Integer
        Dim j As Integer

        'create object of excel
        ExcelApp = CreateObject("Excel.Application")
        ExcelBook = ExcelApp.WorkBooks.Add
        ExcelSheet = ExcelBook.WorkSheets(1)

       dim rowIndex as integer = 1 
       dim colIndex as integer = 2
       
       ''For Headers  
       With ExcelSheet
            For each column as datagridviewcolumn in Me.DataGridView1.columns
               if column.name = "Id" then 
                      .cells(rowindex, 1) = Column.HeaderText
                else 

                .cells(rowindex, colIndex) = Column.HeaderText
                colIndex = ColIndex + 1 
                end if 
            Next
        End With

        

        With ExcelSheet
            For i = 0 To Me.DataGridView1.RowCount-1
               if not isnothing (Me.DataGridView1.Rows(i).Cells(0).value) then
               rowindex = rowIndex + 1 
               ColumnIndex = 2
 
              
                For j = 0 To DataGridView1.Columns.Count - 1
                     if datagridview1.columns(j).name = "Id" then 
                          .cells(rowindex, 1) =   DataGridView1.Rows(i).Cells(j).Value     
                     else 
                        .cells(rowindex, columnIndex ) = DataGridView1.Rows(i).Cells(j).Value
                         ColumnIndex = ColumnIndex + 1 
                     End if 
                Next
             End if 
            Next
        End With

        ExcelApp.Visible = True
        '
        ExcelSheet = Nothing
        ExcelBook = Nothing
        ExcelApp = Nothing

    End Sub

在第一个代码中,您需要尝试进行以下更改(Header datagridview 中的文本不应重复,最好在数据表中添加列名)

      'Adding the Columns
        For Each column As DataGridViewColumn In DataGridView1.Columns
            dt.Columns.Add(column.Name, column.ValueType)
        Next
   'Adding the Rows
        dim dr as datarow 
        For Each row As DataGridViewRow In DataGridView1.Rows
            dr = dt.Newrow 
            For Each cell As DataGridViewCell In row.Cells
                 If not isnothing(cell.value) then

                       dr(datagridview1.columns(cell.ColumnIndex).Name)=  cell.Value
                End if
            Next
            dt.rows.add (dr) 
        Next

我使用了第二个代码。我尝试使用您的代码,但一开始没有用,但后来我注意到您将列索引命名为 ColumnIndex,实际上需要命名为 colIndex,感谢您的帮助。

这是完成的代码,

    Private Sub ExportToExcel()

        Dim ExcelApp As Object, ExcelBook As Object
        Dim ExcelSheet As Object
        Dim i As Integer
        Dim j As Integer

        'create object of excel
        ExcelApp = CreateObject("Excel.Application")
        ExcelBook = ExcelApp.WorkBooks.Add
        ExcelSheet = ExcelBook.WorkSheets(1)

        Dim rowIndex As Integer = 1
        Dim colIndex As Integer = 1

        ''For Headers  
        With ExcelSheet
            For Each column As DataGridViewColumn In Me.DataGridView1.Columns
                If column.Name = "Id" Then
                    .cells(rowIndex, 1) = column.HeaderText
                Else

                    .cells(rowIndex, colIndex) = column.HeaderText
                    colIndex = colIndex + 1
                End If
            Next
        End With


        ''For Rows
        With ExcelSheet
            For i = 0 To Me.DataGridView1.RowCount - 1
                If Not IsNothing(Me.DataGridView1.Rows(i).Cells(0).Value) Then
                    rowIndex = rowIndex + 1
                    colIndex = 1


                    For j = 0 To DataGridView1.Columns.Count - 1
                        If DataGridView1.Columns(j).Name = "Id" Then
                            .cells(rowIndex, 1) = DataGridView1.Rows(i).Cells(j).Value
                        Else
                            .cells(rowIndex, colIndex) = DataGridView1.Rows(i).Cells(j).Value
                            colIndex = colIndex + 1
                        End If
                    Next
                End If
            Next
        End With

        ExcelApp.Visible = True
        '
        ExcelSheet = Nothing
        ExcelBook = Nothing
        ExcelApp = Nothing

    End Sub
    ```