尝试将数据导出到excel时,vb.net的“NullReferenceException未处理”

时间:2017-03-25 09:23:19

标签: excel vb.net datagridview nullreferenceexception

我试图将我的datagridview数据导出到excel,当我在观看教程后运行它时出现了这个错误。

它说“NewOrderSystem_v1.4.exe中发生了'System.NullReferenceException'类型的未处理异常 附加信息:对象引用未设置为对象的实例。“

我现在不知道该怎么办,而且我已经被困了两个星期

有人可以帮助我吗?

Here is the screenshot of the error

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim xlApp As Microsoft.Office.Interop.Excel.Application
    Dim xlWorkbook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlWorksheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim i As Integer
    Dim j As Integer

    xlApp = New Microsoft.Office.Interop.Excel.Application
    xlWorkbook = xlApp.Workbooks.Add(misValue)
    xlWorksheet = xlWorkbook.Sheets("sheet1")


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

    xlWorksheet.SaveAs("C:\Users\Julian\Documents\Visual Studio 2013\Projects\NewOrderSystem_v1.2\NewOrderSystem.xlsx")
    xlWorkbook.Close()
    xlApp.Quit()

    releaseObject(xlApp)
    releaseObject(xlWorkbook)
    releaseObject(xlWorksheet)

    MsgBox("You can find the file in this location: C:\Users\Julian\Documents\Visual Studio 2013\Projects\NewOrderSystem_v1.2\NewOrderSystem.xlsx")
    Dim res As MsgBoxResult
    res = MsgBox("Process Completed, Would you like to open the file?", MsgBoxStyle.YesNo)
    If (res = MsgBoxResult.Yes) Then
        Process.Start("C:\Users\Julian\Documents\Visual Studio 2013\Projects\NewOrderSystem_v1.2\NewOrderSystem.xlsx")
    End If
End Sub
Private Sub releaseObject(ByVal obj As Object)
    Try
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'Database1DataSet.Table1' table. You can move, or remove it, as needed.
    Me.Table1TableAdapter.Fill(Me.Database1DataSet.Table1)
    'TODO: This line of code loads data into the 'NewOrderSystemDataSet.NewOrderSystemTable' table. You can move, or remove it, as needed.
    Me.NewOrderSystemTableTableAdapter.Fill(Me.NewOrderSystemDataSet.NewOrderSystemTable)

End Sub

结束班

这是我的代码

感谢所有愿意帮助的人

Added the screenshot of the null variable, so how can I make this not null?

0 个答案:

没有答案