title: VB.NET Export to Excel with header
body: <p>I am uploading an Excel file into a datagridview. This file has a view headers 
  (Case, Paid, Curr, Narrative1, Narrative2, Account, Grouping).</p>
  
  <p>However, some of these fields could be empty for whatever reason (invalid entry, case number doesn't match anything, whatever).</p>
  
  <p>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.</p>
  
  <p>However, I need to export these two files back to Excel, and this is where I am having errors.</p>
  
  <p>For example, my DGV looks like this:
  <img src="https://i.stack.imgur.com/RWlbO.jpg" alt="enter image description here"></p>
  
  <p>My code to export this to Excel is this:</p>
  
  <pre><code>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 &amp; FileName &amp; "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
  </code></pre>
  
  <p>But I am getting an error message saying 
  <img src="https://i.stack.imgur.com/UPzLy.jpg" alt="enter image description here"></p>
  
  <p>And it points to the line </p>
  
  <pre><code>xlWorkSheet.Cells(i + 2, j + 1) = DataGridView2(j, i).Value.ToString()
  </code></pre>
  
  <p>Would anyone know how to fix this? In theory, any of those fields could be empty.</p>
  
  <p>I'm using Visual Studio 2010.</p>