0

I am trying to export the contents of a datagridview to an excel spreadsheet, regardless of how I attack it I come up with one of two errors. the first error is "option strict on disallows late binding" or the second error is System.NullReferenceException: 'Object reference not set to an instance of an object.' open to any ideas, cheers and thanks in advance Darren

the code I am uploading creates the second error

the imports line, and the reference for excel is loaded.

Imports Excel = Microsoft.Office.Interop.Excel



 Private Sub SaveToExcelButton_Click(sender As Object, e As EventArgs) 'Handles SaveToExcelButton.Click
        Dim excelapp As Excel.Application
        Dim excelworkbook As Excel._Workbook
        Dim excelWorkSheet As Excel._Worksheet = CType(excelworkbook.Worksheets(1), Excel.Worksheet)
        Dim misValue As Object = System.Reflection.Missing.Value
        ' excelapp = New Excel.ApplicationClass
        excelworkbook = excelapp.Workbooks.Add(misValue)
        excelWorkSheet = excelworkbook.Sheets("sheet1")


        excelWorkSheet.Cells(1, 1).Value = "Driver"
        excelWorkSheet.Cells(1, 2).Value = "Fuel"
        excelWorkSheet.Cells(1, 3).Value = "Volume Per Hour"
        excelWorkSheet.Cells(1, 4).Value = "Fuel Per Lap"
        excelWorkSheet.Cells(1, 5).Value = "Time"
        excelWorkSheet.Cells(1, 6).Value = "Speed"

        For rowIdx As Integer = 0 To Grid1.Rows.Count - 1
            excelWorkSheet.Cells(rowIdx + 2, 1).Value = Grid1.Rows(rowIdx).Cells(2).Value
            excelWorkSheet.Cells(rowIdx + 2, 2).Value = Grid1.Rows(rowIdx).Cells(5).Value
            excelWorkSheet.Cells(rowIdx + 2, 3).Value = Grid1.Rows(rowIdx).Cells(6).Value
            excelWorkSheet.Cells(rowIdx + 2, 4).Value = Grid1.Rows(rowIdx).Cells(7).Value
            excelWorkSheet.Cells(rowIdx + 2, 5).Value = Grid1.Rows(rowIdx).Cells(9).Value
            excelWorkSheet.Cells(rowIdx + 2, 6).Value = Grid1.Rows(rowIdx).Cells(10).Value
        Next
    End Sub
Dazza
  • 9
  • 5
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – derpirscher Mar 28 '23 at 06:51
  • Not a direct answer, but there are many well documented tools around that simplify Excel interactions (EPPlus, OpenXml for example). You will also find this much simpler if you process the backing data for the DataGridView – Hursey Mar 28 '23 at 19:17
  • Thanks for the link, it was sort of helpful, I think I am just a little out of my depth with this stuff sometime. I have managed to get it to work, by removing everything after the ctype statement. Much more to learn, thanks for pointing me in the right direction, cheers Daz – Dazza Mar 29 '23 at 06:41

0 Answers0