04-08-24, 09:15 PM
كود :
Private Sub ExportToExcel()
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
'create object of excel
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
Dim rowIndex As Integer = 1
Dim colIndex As Integer = 1
''For Headers
With ExcelSheet
For Each column As DataGridViewColumn In Me.DataGridView1.Columns
If column.Name = "Id" Then
.cells(rowIndex, 1) = column.HeaderText
Else
.cells(rowIndex, colIndex) = column.HeaderText
colIndex = colIndex + 1
End If
Next
End With
''For Rows
With ExcelSheet
For i = 0 To Me.DataGridView1.RowCount - 1
If Not IsNothing(Me.DataGridView1.Rows(i).Cells(0).Value) Then
rowIndex = rowIndex + 1
colIndex = 1
For j = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Columns(j).Name = "Id" Then
.cells(rowIndex, 1) = DataGridView1.Rows(i).Cells(j).Value
Else
.cells(rowIndex, colIndex) = DataGridView1.Rows(i).Cells(j).Value
colIndex = colIndex + 1
End If
Next
End If
Next
End With
ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
MsgBox("")
End Sub