hello
please help
How to export data from datagridview to excel
when i click button1 then open excel but blank data export from datagridview
when i click button2 then a error show
please help
http://www.mediafire.com/file/vcm9sg3o8qzpp5t/Capture.PNG
http://www.mediafire.com/file/6r5xgztxzqhbz1z/Button+2+error.png
What I have tried:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim app_xls As Object
Dim lig_cpt, col_cpt As Integer
app_xls = CreateObject("excel.application")
app_xls.workbooks.add()
app_xls.visible = True
'kkkkkkk
Try
For col_cpt = 0 To DataGridView1.ColumnCount - 4
app_xls.activesheet.cell(1, col_cpt, +1).value = DataGridView1.Columns(col_cpt).HeaderText
Next
For lig_cpt = 0 To DataGridView1.Rows.Count - 1
For col_cpt = 0 To DataGridView1.ColumnCount - 4
If IsNumeric(DataGridView1.Item(col_cpt, lig_cpt).Value) Then
app_xls.activesheet.cells(lig_cpt + 2, col_cpt + 1).value = CDbl(DataGridView1.Item(col_cpt, lig_cpt).Value)
Else
app_xls.activesheet.cells(lig_cpt + 2, col_cpt + 1).value = DataGridView1.Item(col_cpt, lig_cpt).Value
End If
Next
Next
Catch ex As Exception
End Try
End Sub
======================================================
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
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)
With ExcelSheet
For i = 1 To Me.DataGridView1.RowCount
.cells(i, 1) = Me.DataGridView1.Rows(i - 1).Cells("id").value
For j = 1 To DataGridView1.Columns.Count - 1
.cells(i, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
Next
Next
End With
ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End Sub