title: VB.net DataGridView to Excel
body: <p>I’m using VB.net on Microsoft visual studio 2017, to create a little App and I’m having a problem with the code that I’m using to export my Datagridview to excel. It exports everything but the last row of my data. Any idea how I can fix this?</p>
  
  <pre><code>Imports Excel = Microsoft.Office.Interop.Excel
  Imports Microsoft.Office
  Imports Microsoft.Office.Interop
  Imports System.IO
  
  Private Sub ExportToExcel()
          ' Creating a Excel object.
          Dim excel As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application()
          Dim workbook As Microsoft.Office.Interop.Excel._Workbook = excel.Workbooks.Add(Type.Missing)
          Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = Nothing
  
          Try
  
              worksheet = workbook.ActiveSheet
  
              worksheet.Name = "ExportedFromDatGrid"
  
              Dim cellRowIndex As Integer = 1
              Dim cellColumnIndex As Integer = 1
  
              'Write headers
              For j As Integer = 0 To DataGridView_Kontakte.Columns.Count - 2
                  worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView_Kontakte.Columns(j).HeaderText
                  cellColumnIndex += 1
              Next
              cellColumnIndex = 1
              cellRowIndex += 1
  
              'Loop through each row and read value from each column.
              For i As Integer = 0 To DataGridView_Kontakte.Rows.Count - 2
                  For j As Integer = 0 To DataGridView_Kontakte.Columns.Count - 1
                      ' Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
                      worksheet.Cells(cellRowIndex, cellColumnIndex) = DataGridView_Kontakte.Rows(i).Cells(j).Value.ToString()
                      cellColumnIndex += 1
                  Next
                  cellColumnIndex = 1
                  cellRowIndex += 1
              Next
  
              'Getting the location and file name of the excel to save from user.
              Dim saveDialog As New SaveFileDialog()
              saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"
              saveDialog.FilterIndex = 2
  
              If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                  workbook.SaveAs(saveDialog.FileName)
                  MessageBox.Show("Export Successful")
              End If
          Catch ex As System.Exception
              MessageBox.Show(ex.Message)
          Finally
              excel.Quit()
              workbook = Nothing
              excel = Nothing
          End Try
  
      End Sub
  </code></pre>