Private Sub create(ByVal sDatabaseName As String)
Dim dsTables As DataSet = New DataSet
'Get all Tables from database
dsTables = getAllTables(sDatabaseName)
'Create Excel Application, Workbook, and WorkSheets
Dim xlExcel As New Excel.Application
Dim xlBooks As Excel.Workbooks
Dim xlBook As Excel.Workbook
Dim tblSheet As Excel.Worksheet
Dim xlCells As Excel.Range
Dim sFile As String
'File name for the excel file
sFile = Server.MapPath("~\Sheets\" & sDatabaseName & "_data.xls")
xlExcel.Visible = False : xlExcel.DisplayAlerts = False
xlBooks = xlExcel.Workbooks
xlBook = xlBooks.Add
For i As Integer = 0 To dsTables.Tables.Count - 1
tblSheet = xlBook.Worksheets.Add
tblSheet.Name = dsTables.Tables(i).TableName
xlCells = tblSheet.Cells
'Fill all cells with data
GenerateExcelFile(dsTables.Tables(i), xlCells)
Next
'Remove initial excel sheets. Within a try catch because the database
'could be empty (a workbook without worksheets is not allowed)
Try
Dim SheetCount As Integer = xlExcel.Sheets.Count
CType(xlExcel.Sheets(SheetCount - 0), Excel.Worksheet).Delete()
CType(xlExcel.Sheets(SheetCount - 1), Excel.Worksheet).Delete()
CType(xlExcel.Sheets(SheetCount - 2), Excel.Worksheet).Delete()
Catch ex As Exception
End Try
'Save the excel file
xlBook.SaveAs(sFile)
'Make sure all objects are disposed
xlBook.Close()
xlExcel.Quit()
ReleaseComObject(xlCells)
ReleaseComObject(tblSheet)
ReleaseComObject(xlBook)
ReleaseComObject(xlBooks)
ReleaseComObject(xlExcel)
xlExcel = Nothing
xlBooks = Nothing
xlBook = Nothing
tblSheet = Nothing
xlCells = Nothing
'Let the Garbage Collector know it can get to work
GC.Collect()
'Export Excel for download
Try
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(sFile))
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.WriteFile(sFile)
HttpContext.Current.Response.End()
Catch ex As Exception
'An exception will be thrown, but can just be ignored
End Try
End Sub