Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim MyExcel As New Microsoft.Office.Interop.Excel.Application()
MyExcel.Application.Workbooks.Add()
MyExcel.Visible = True
'擷取标題
Dim Cols As Integer
For Cols = 1 To DataGridView1.Columns.Count
MyExcel.Cells(1, Cols) = DataGridView1.Columns(Cols - 1).HeaderText
Next
'往excel表裡添加資料()
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim j As Integer
For j = 0 To DataGridView1.ColumnCount - 1
If Me.DataGridView1(j, i).Value Is System.DBNull.Value Then
MyExcel.Cells(i + 2, j + 1) = ""
Else
MyExcel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString
End If
Next j
Next i
End Sub
注明:需要在程式裡添加Excel的引用。