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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值