VB.NET将DataGridView导出到Excel

时间:2018-02-23 15:11:28

标签: excel vb.net export

当我尝试将DataGridView导出到Excel时,我收到错误“对象变量或未设置块变量”。

我已粘贴下面的代码;

不太确定错误发生的位置,任何帮助都会受到大力赞赏。

Imports System.Data.SqlClient
Public Class Form1
    Public Property MetroGrid1 As Object

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ValidFromDate.Font = New Font(ValidFromDate.Font, FontStyle.Bold)
        ValidFromDate.Text = "Valid From:" & " " & DateTime.Now.ToString("dd MMMM,yyyy") & " @ " & DateTime.Now.ToString("hh:mm:ss tt")
        Me.Vw_Barcode_CheckTableAdapter.Fill(Me.InfoDataSet.vw_Barcode_Check)

    Private Sub ExportToExcelBtn_Click(sender As Object, e As EventArgs) Handles ExportToExcelBtn.Click
        ExportToExcel()
        Dim DateLastRun As DateTime = DateTime.Now
        LastExport.Text = DateTime.Now
        My.Settings.LastRunDate = LastExport.Text
    End Sub
    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 = "Barcodes"

            Dim cellRowIndex As Integer = 1
            Dim cellColumnIndex As Integer = 1

            'Loop through each row and read value from each column.
            For i As Integer = 0 To MetroGrid1.Rows.Count - 2
                For j As Integer = 0 To MetroGrid1.Columns.Count - 1
                    ' Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
                    If cellRowIndex = 1 Then
                        worksheet.Cells(cellRowIndex, cellColumnIndex) = MetroGrid1.Columns(j).HeaderText
                    Else
                        worksheet.Cells(cellRowIndex, cellColumnIndex) = MetroGrid1.Rows(i).Cells(j).Value.ToString()
                    End If
                    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 With {
                .Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*",
                .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
End Class

0 个答案:

没有答案