0

我正在尝试将数据网格控件中的值导出到 Excel。我遇到的问题是,调试后,当我单击按钮时,应用程序就会卡住。我也无法关闭表格。我必须单击调试按钮。excel文件也没有创建。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.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.ApplicationClass
    xlWorkBook = xlApp.Workbooks.Add(misValue)
    xlWorkSheet = CType(xlWorkBook.Worksheets.Item("sheet1"), Microsoft.Office.Interop.Excel.Worksheet)
    For i = 0 To DataGridView1.RowCount - 2
        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("D:\vbexcel.xlsx")
    xlWorkBook.Close()
    xlApp.Quit()

    xlApp = Nothing
    xlWorkBook = Nothing
    xlWorkSheet = Nothing

    MsgBox("You can find the file D:\vbexcel.xlsx")

End Sub
4

1 回答 1

0

尝试这个 ...

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

        xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()

    Next
Next
于 2013-07-26T16:13:47.490 回答