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
|