DataGridView導出到Excel

Imports Excel = Microsoft.Office.Interop.Excel
'Excel,代碼可按該名稱而不是完全限定字符串來引用 namespace。

Module ModExcel
    Sub CreateWorkbook(ByRef dgv As DataGridView, ByVal filePath As String, ByVal strExcelName As String)
        Dim excelApp As Excel.Application = Nothing
        Dim wkbk As Excel.Workbook
        Dim sheet As Excel.Worksheet
        Dim i As Integer
        Dim j As Integer
        Dim prbExporDate As FrmProcessBar

        Try
            excelApp = New Excel.Application
            wkbk = excelApp.Workbooks.Add()
            sheet = CType(wkbk.Sheets.Add(), Excel.Worksheet)
            sheet.Name = strExcelName
            '' Write a column of values.
            prbExporDate = New FrmProcessBar

            With dgv
                For i = 1 To .ColumnCount - 1
                    sheet.Cells(1, i) = .Columns(i).HeaderCell.Value
                Next
                With prbExporDate
                    .PrbExport.Minimum = 0
                    .PrbExport.Maximum = dgv.RowCount - 1
                    '.LblProcess.Text = "正在導出,請稍等。。。"
                    .Refresh()
                    .Show()
                End With
                For j = 0 To .RowCount - 1
                    prbExporDate.PrbExport.Value = j
                    For i = 1 To .ColumnCount - 1
                        If IsDBNull(.Rows(j).Cells(i).Value) = False Then
                            '注意:.Value.toString 如果原Value is null 引發nullreferenceexception
                            '異常
                            sheet.Cells(j + 2, i) = .Rows(j).Cells(i).Value
                        End If
                    Next
                Next
            End With
            prbExporDate.Visible = False
            excelApp.DisplayAlerts = False
            Dim folderPath = My.Computer.FileSystem.GetParentPath(filePath)
            If Not My.Computer.FileSystem.DirectoryExists(folderPath) Then
                My.Computer.FileSystem.CreateDirectory(folderPath)
            End If
            wkbk.SaveAs(filePath)
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "ExportData Error!", _
            MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            sheet = Nothing
            wkbk = Nothing
            ' Close Excel.
            excelApp.Quit()
            excelApp = Nothing
            prbExporDate = Nothing
        End Try
    End Sub

End Module

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章