Search code examples
vb.netdatagridviewexport-to-excel

VB.NET Export to Excel with header


I am uploading an Excel file into a datagridview. This file has a view headers (Case, Paid, Curr, Narrative1, Narrative2, Account, Grouping).

However, some of these fields could be empty for whatever reason (invalid entry, case number doesn't match anything, whatever).

Depending on if I can upload this line to my database yes or no, I am filling two different datagridviews. datagridview2 for all errors, datagridview3 for all successful ones.

However, I need to export these two files back to Excel, and this is where I am having errors.

For example, my DGV looks like this: enter image description here

My code to export this to Excel is this:

Private Sub ExportErrors(FileName)
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim path As String
    Dim i As Int16, j As Int16

    xlApp = New Excel.ApplicationClass
    xlWorkBook = xlApp.Workbooks.Add(misValue)
    xlWorkSheet = xlWorkBook.Sheets("sheet1")


    For i = 0 To DataGridView2.RowCount - 2
        For j = 0 To DataGridView2.ColumnCount - 1
            For k As Integer = 1 To DataGridView2.Columns.Count
                xlWorkSheet.Cells(1, k) = DataGridView2.Columns(k - 1).HeaderText
                xlWorkSheet.Cells(i + 2, j + 1) = DataGridView2(j, i).Value.ToString()
            Next
        Next
    Next

    path = ErrorProcessedDirectory & FileName & "Error.xls"

    xlWorkBook.SaveAs(path, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
     Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
    xlWorkBook.Close(True, misValue, misValue)
    xlApp.Quit()

    releaseObject(xlWorkSheet)
    releaseObject(xlWorkBook)
    releaseObject(xlApp)

    MessageBox.Show("Export Successful")
End Sub

But I am getting an error message saying enter image description here

And it points to the line

xlWorkSheet.Cells(i + 2, j + 1) = DataGridView2(j, i).Value.ToString()

Would anyone know how to fix this? In theory, any of those fields could be empty.

I'm using Visual Studio 2010.


Solution

  • try removing the ToString portion of your datagridview value like this:

    xlWorkSheet.Cells(i + 2, j + 1).value = DataGridView2(j, i).Value
    

    I believe the error is caused because Nothing / Null does not have the ToString Function