将datagrid值导出为ex​​cel

时间:2013-07-26 15:32:35

标签: vb.net

我正在尝试将数据网格控件中的值导出为ex​​cel。我遇到的问题是,在调试之后,当我单击按钮时,应用程序就会卡住。我也无法关闭表格。我必须单击调试按钮。也没有创建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

1 个答案:

答案 0 :(得分: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