不将datagridview数据导出到excel vb.net

时间:2016-09-14 19:16:56

标签: vb.net for-loop foreach rows export-to-excel

我将数据网格视图导出到excel,当我导出包含数据的行仅一年时它运行得很好,但是当我做了2年或更长时间它没有导出,我的winform崩溃。总之,我有要导出的135159行。

这是我的代码

        Dim exApp As New Microsoft.Office.Interop.Excel.Application

        Dim exLibro As Microsoft.Office.Interop.Excel.Workbook

        Dim exHoja As Microsoft.Office.Interop.Excel.Worksheet

        Try

            exLibro = exApp.Workbooks.Add

            exHoja = exLibro.Worksheets.Add()


            Dim NCol As Integer = dgvDatos.ColumnCount

            Dim NRow As Integer = dgvDatos.RowCount

            'this is to export columns
            For i As Integer = 1 To NCol

                exHoja.Cells.Item(1, i) = dgvDatos.Columns(i - 1).Name.ToString

            Next

        'this is to export all the rows
        For Fila As Integer = 0 To NRow - 1

            For Col As Integer = 0 To NCol - 1

                exHoja.Cells.Item(Fila + 2, Col + 1) = dgvDatos.Item(Col, Fila).Value

            Next
        Next

如果你能帮助我,那就太好了,谢谢!!

1 个答案:

答案 0 :(得分:0)

试试这段代码:

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    #makes it so I can config the database from anywhere
    #change the line below
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

路径位于Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.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 HEADERS For i = 1 To DataGridView1.ColumnCount xlWorkSheet.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText 'FOR ITEMS For j = 1 To DataGridView1.RowCount xlWorkSheet.Cells(j + 1, i) = DataGridView1(i - 1, j - 1).Value.ToString() Next Next xlWorkSheet.SaveAs("D:\vbexcel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) MsgBox("You can find the file D:\vbexcel.xlsx") 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 End Class ,文件名为D: 注意:选择“否”将收到错误,因为它将在同一路径中使用相同的文件名替换该文件。始终选择“是”以替换现有文件。