Question : how to export datatable to Excel using Save dialog in VB.NET

how to export datatable to Excel using Save dialog in VB.NET

Answer : how to export datatable to Excel using Save dialog in VB.NET

Try this code... Here is the function which takes the datatable in which data resides and the file  path where you wants to save the excel file.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
Function ExportToExcel(ByVal dtGridData As DataTable, ByVal FilePath As String) As Boolean
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Try
            Application.DoEvents()
            xlApp = New Excel.Application
            xlApp.DisplayAlerts = False
            xlApp.Workbooks.Add()
            xlApp.Workbooks(1).SaveAs(FilePath)
            xlWorkBook = xlApp.Workbooks.Open(FilePath)
            xlWorkSheet = xlWorkBook.Worksheets("Sheet1") 
            Dim dtRowCount As Integer = dtGridData.Rows.Count
            Dim dtColCount As Integer = dtGridData.Columns.Count
            Dim objXlColHeaderData(1, dtGridData.Columns.Count) As Object
            Application.DoEvents()
            For i As Integer = 0 To dtColCount - 1
                objXlColHeaderData(0, i) = dtGridData.Columns(i).ColumnName
            Next
            Dim objXlData(dtRowCount, dtColCount) As Object
            For iRow As Integer = 0 To dtRowCount - 1
                Application.DoEvents()
                For iCol As Integer = 0 To dtColCount - 1
                    Application.DoEvents()
                    If Not IsDBNull(dtGridData.Rows(iRow).Item(iCol)) Then
                        objXlData(iRow, iCol) = dtGridData.Rows(iRow).Item(iCol)
                    Else
                        objXlData(iRow, iCol) = ""
                    End If
                Next
            Next
            Dim xlRange As Excel.Range = xlWorkSheet.Range("A1")
            xlRange = xlRange.Resize(dtRowCount, dtColCount)
            xlRange.Value = objXlColHeaderData
            xlRange = xlWorkSheet.Range("A2")
            xlRange = xlRange.Resize(dtRowCount, dtColCount)
            xlRange.Value = objXlData
            Application.DoEvents()
            xlWorkBook.SaveAs(FilePath)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "ErrorIn ExportToExcel", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            xlWorkSheet = Nothing
            xlWorkBook.Close()
            xlWorkBook = Nothing
            xlApp.Quit()
            xlApp = Nothing
        End Try
    End Function
Random Solutions  
 
programming4us programming4us