Hi, I am having problem with my coding below when I would like to export the data from GridView to Excel Spreadsheet. Appreciate if you could share your valuable comment. Thanks
Error Message = Class 'System.Web.UI.WebControls.GridView' cannot be indexed becasue it has no default property.
Error Line = xlWorkSheet.Cells(i + 1, j + 1) = GridView1(j, i).Value
Coding
Private Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim xlApp As excel.Application
Dim xlWorkBook As excel.Workbook
Dim xlWorkSheet As excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
Dim x As Integer
Dim iC As Integer
xlApp = New excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For iC = 0 To GridView1.Columns.Count - 1
xlWorkSheet.Cells(1, iC + 1).Value = GridView1.Columns(iC).HeaderText
xlWorkSheet.Cells(1, iC + 1).font.bold = True
Next iC
For i = 0 To GridView1.Rows.Count - 1
For j = 0 To GridView1.Columns.Count - 1
xlWorkSheet.Cells(i + 1, j + 1) = GridView1(j, i).Value
Next
Next
xlWorkSheet.SaveAs("C:\Excel\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("File has been saved as C:\Excel\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class