多个数据网格到一个Excel工作表

时间:2014-08-01 06:11:43

标签: vb.net

我有以下代码,它会将记录从我的数据网格传输到我的Excel电子表格。 目前,此代码适用于一个数据网格到Excel工作表。现在我需要改进下面的代码,以便它可以用于多个数据网格。我希望帮助扩展此代码,以便我可以将记录从3个数据网格拉到另一个下面的同一个Excel工作表。

Dim excel As Microsoft.Office.Interop.Excel.Application
Try
excel = New Microsoft.Office.Interop.Excel.Application
excel.Workbooks.Open("C:\Satish\TestExcel\vbexcel.xlsx")
Dim i As Integer, j As Integer
Dim diff As Integer = 1
' if you want column header from dgv elese omit the block 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
For j = 0 To DataGridView1.ColumnCount - 1
excel.Worksheets(1).cells(1, j + 1) = DataGridView1.Columns(j).Name
Next
diff += 1
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
For i = 0 To DataGridView4.RowCount - 1

If DataGridView4.Rows(i).IsNewRow = False Then
For j = 0 To DataGridView4.ColumnCount - 1

excel.Worksheets(1).cells(i + diff, j + 1) = DataGridView4.Item(j, i).Value
Next
End If
Next
excel.Worksheets(1).select()
excel.ActiveWorkbook().Save()
excel.Workbooks.Close()
excel.Quit()
excel = Nothing
Catch ex As System.Runtime.InteropServices.COMException
MessageBox.Show("Error accessing Excel: " + ex.ToString())
Catch ex As Exception
MessageBox.Show("Error: " + ex.ToString())
End Try

1 个答案:

答案 0 :(得分:0)

试试这段代码:

Dim intExcelRow As Integer = 1

For i As Integer = 1 To 3

    Dim YourDataGridView As DataGridView = Me.Controls("YourDataGridView" & i)

    'header of the first DataGridView only
    'remove If i = 1 if you need to print 3 different headers
    If i = 1 Then

        For intColumn = 0 To YourDataGridView.ColumnCount - 1
            excel.Worksheets(1).cells(intExcelRow, intColumn + 1) = YourDataGridView.Columns(intColumn).Name
        Next intColumn

        intExcelRow = intExcelRow + 1

    End If

    For intRow = 0 To YourDataGridView.RowCount - 1

        If YourDataGridView.Rows(intRow).IsNewRow = False Then

            For intColumn = 0 To YourDataGridView.ColumnCount - 1
                excel.Worksheets(1).cells(intExcelRow, intColumn + 1) = YourDataGridView.Item(intColumn, intRow).Value
            Next intColumn

            intExcelRow = intExcelRow + 1

        End If

    Next intRow

Next i