473,763 Members | 5,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Export complete database to excel file

3 New Member
First of all, I need to give some credit to Mahesh Chand for providing me with an excellent basis to export data to excel.

What does this code do:
As the title says, this code is capable of extracting all tables and it's data from any given database! I was searching the net for a program like this, but I didn't come accross any (free) versions. So I decided to write it myself.


To get this code to work, you need to add a reference to Excel.dll by using Add Reference on the project and selecting Microsoft Excel 9.0 (or 10.0) Object Library from the COM tab on the Add Reference dialog.

And then import the following namespace:

Expand|Select|Wrap|Line Numbers
  1. Imports System.Runtime.InteropServices.Marshal
Now add the following class to your project:

Expand|Select|Wrap|Line Numbers
  1. Private Sub create(ByVal sDatabaseName As String)
  2. Dim dsTables As DataSet = New DataSet
  3.  
  4. 'Get all Tables from database
  5. dsTables = getAllTables(sDatabaseName)
  6. 'Create Excel Application, Workbook, and WorkSheets
  7. Dim xlExcel As New Excel.Application
  8. Dim xlBooks As Excel.Workbooks
  9. Dim xlBook As Excel.Workbook
  10. Dim tblSheet As Excel.Worksheet
  11. Dim xlCells As Excel.Range
  12. Dim sFile As String
  13. 'File name for the excel file
  14. sFile = Server.MapPath("~\Sheets\" & sDatabaseName & "_data.xls")
  15. xlExcel.Visible = False : xlExcel.DisplayAlerts = False
  16. xlBooks = xlExcel.Workbooks
  17. xlBook = xlBooks.Add
  18. For i As Integer = 0 To dsTables.Tables.Count - 1
  19.     tblSheet = xlBook.Worksheets.Add
  20.     tblSheet.Name = dsTables.Tables(i).TableName
  21.     xlCells = tblSheet.Cells
  22.     'Fill all cells with data 
  23.     GenerateExcelFile(dsTables.Tables(i), xlCells) 
  24. Next
  25. 'Remove initial excel sheets. Within a try catch because the database 
  26. 'could be empty (a workbook without worksheets is not allowed)
  27. Try
  28.     Dim SheetCount As Integer = xlExcel.Sheets.Count
  29.     CType(xlExcel.Sheets(SheetCount - 0), Excel.Worksheet).Delete()
  30.     CType(xlExcel.Sheets(SheetCount - 1), Excel.Worksheet).Delete()
  31.     CType(xlExcel.Sheets(SheetCount - 2), Excel.Worksheet).Delete()
  32. Catch ex As Exception
  33. End Try
  34. 'Save the excel file
  35. xlBook.SaveAs(sFile)
  36. 'Make sure all objects are disposed
  37. xlBook.Close()
  38. xlExcel.Quit()
  39. ReleaseComObject(xlCells)
  40. ReleaseComObject(tblSheet)
  41. ReleaseComObject(xlBook)
  42. ReleaseComObject(xlBooks)
  43. ReleaseComObject(xlExcel)
  44. xlExcel = Nothing
  45. xlBooks = Nothing
  46. xlBook = Nothing
  47. tblSheet = Nothing
  48. xlCells = Nothing
  49. 'Let the Garbage Collector know it can get to work
  50. GC.Collect()
  51. 'Export Excel for download
  52. Try
  53. HttpContext.Current.Response.ContentType = "application/octet-stream"
  54. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(sFile))
  55. HttpContext.Current.Response.Clear()
  56. HttpContext.Current.Response.WriteFile(sFile)
  57. HttpContext.Current.Response.End()
  58. Catch ex As Exception
  59. 'An exception will be thrown, but can just be ignored
  60. End Try
  61. End Sub
To generate the individual sheets, the following Sub is used:

Expand|Select|Wrap|Line Numbers
  1. Private Sub GenerateExcelFile(ByRef table As DataTable, ByVal xlCells As Excel.Range)
  2. Dim dr As DataRow, ary() As Object
  3. Dim iRow As Integer, iCol As Integer
  4. 'Output Column Headers
  5. For iCol = 0 To table.Columns.Count - 1
  6.     xlCells(1, iCol + 1) = table.Columns(iCol).ToString
  7.     xlCells(1).EntireRow.Font.Bold = True
  8. Next
  9. 'Output Data
  10. For iRow = 0 To table.Rows.Count - 1
  11.     dr = table.Rows.Item(iRow)
  12.     ary = dr.ItemArray
  13.     For iCol = 0 To UBound(ary)
  14.         xlCells(iRow + 2, iCol + 1) = ary(iCol).ToString
  15.         Response.Write(ary(iCol).ToString & vbTab)
  16.     Next
  17. Next
  18. xlCells.Columns.AutoFit()
  19. End Sub
And now the trick to getting all tables and data from a database:

Expand|Select|Wrap|Line Numbers
  1. Public database as String
  2. Public ReadOnly Property getAllTables(ByVal sDB As String) As DataSet
  3.     Get
  4.         database = sDB
  5.         Dim m_dshelp As DataSet = New DataSet
  6.         getRequestedAllTables(m_dshelp)
  7.         Return m_dshelp
  8.     End Get
  9. End Property
  10.  
  11. Private Function getRequestedAllTables(ByRef p_dataset As DataSet) As Boolean
  12. 'Retrieve all tablenames from the database:
  13. Dim sSQL As String
  14. Dim dsTables As DataSet = New DataSet
  15. sSQL = "SELECT [TableName] = so.name, [RowCount] = MAX(si.rows) " & _
  16. "FROM sysobjects so, sysindexes si " & _
  17. "WHERE so.xtype = 'U' AND si.id = OBJECT_ID(so.name) AND si.rows > 0 " & _
  18. "GROUP BY so.name " & _
  19. "ORDER BY 2 DESC"
  20. getData(sSQL, "Tables", dsTables)
  21. 'Loop thrue all tables and do a SELECT *. Then add them to the dataset
  22. For i As Integer = 0 To dsTables.Tables(0).Rows.Count - 1
  23.     sSQL = "SELECT * FROM " & dsTables.Tables(0).Rows(i).Item(0)
  24.     getData(sSQL, dsTables.Tables(0).Rows(i).Item(0), p_dataset)
  25. Next
  26. End Function
  27.  
  28. Private Function getData(ByVal p_sql As String, ByVal p_table As String, ByRef pdataset As DataSet) As Boolean
  29. Dim objDataAdapter As SqlDataAdapter
  30. Dim objcommand As SqlCommand
  31. objcommand = New SqlCommand(p_sql, getConnection)
  32. objDataAdapter = New SqlDataAdapter(objcommand)
  33. objDataAdapter.Fill(pdataset, p_table)
  34. End Function
  35.  
  36. Private Function getConnection() As SqlConnection
  37. If (ConfigurationManager.AppSettings("SQLPW") <> "") Then
  38.     getConnection = New SqlConnection("Server=" & _
  39.     ConfigurationManager.AppSettings("SQLserver") & ";password=" & _
  40.     ConfigurationManager.AppSettings("SQLPW") & "; user=" & _
  41.     ConfigurationManager.AppSettings("SQLUser") & ";database=" & database)
  42. Else
  43.     getConnection = New SqlConnection("Data Source=" & _
  44.    ConfigurationManager.AppSettings("SQLserver") & ";Initial Catalog=" & _
  45.     database & ";Integrated Security=True")
  46. End If
  47. End Function
That's all there is to it!! Happy Coding!
Mar 10 '08 #1
1 6690
Sidewinder2
7 New Member
hi,

could you please tell me where can i find the Excel.dll as a free download. i don't find Excel.dll as a free download!.

Thanks!
Sep 18 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

11
4202
by: Mike MacSween | last post by:
My client has an MS Access database application on her local machine. I have full access to that in terms of changing the design. I've got a simple PHP/MySql application on shared hosting, so no direct access to the db server. I'd like to give her the facility to export the information in her local Access application to the shared PHP/MySql site. From one command button (or similar) in the Access application.
1
5033
by: Matt | last post by:
I have an ASP page that calls ASP routines that I created that execute a database query and return the results to a recordset. I then iterate through the recordset and display the data in a table. Before I iterate through the recordset I instruct the browser that the content type is Excel using the following line: (Response.ContentType = "application/vnd.ms-excel") This works fine with Excel 2003 but with older versions (I tested Excel...
6
13142
by: Robin Cushman | last post by:
Hi all, I need some help -- I'm working with an A2K database, using DAO, and am trying to read records into a Crystal Report and then export it to a folder on our network as an Excel spreadsheet. I'm having trouble with my code at the point at which it hits ".ReadRecords" -- the module just runs and runs without generating anything. I've gotten this code to correctly save .rpt files without any data, but not with data, nor have I been...
5
31923
by: Simon | last post by:
Dear reader, With the export command you can export a query to Excel. By activate this command a form pop's up with the following text:
1
9778
by: smaczylo | last post by:
Hello, I've recently been asked to work with Microsoft Access, and while I feel quite comfortable with Excel, I'm at a complete loss with databases. If someone could help me with this issue I'm having I'd be most appreciative. The database is already constructed, I'm just wanting to export the data to an excel file. In short, I'm hoping to export two Tables (or queries...not sure which to use - they both seem to have the same data) in...
1
10502
by: CoolFactor | last post by:
MY CODE IS NEAR THE BOTTOM I want to export this Access query into Excel using a command button on an Access form in the following way I describe below. Below you will find the simple query I am trying to export to Excel using a command in an Access Form. RowID strFY AccountID CostElementWBS 1 2008 1 7 2 2008 1 7 I want to...
7
28903
Merlin1857
by: Merlin1857 | last post by:
Its great producing data for users to look at in your web pages and generally that is sufficient for their needs but sometimes you may want to supply your user with the data in a form they can actually do something more with. This code shows you how to display data from your database and then how to give that data to the user in the form of a useable Excel spreadsheet which they can then take away and play with themselves. The way I have shown...
3
7162
by: =?Utf-8?B?YzY3NjIyOA==?= | last post by:
Hi all, I have a question for you. I have a .csv file which has many lines of data. Each line has many data fields which are delimited by ",". Now I need to extract part of data from this file but save it as an excel file. The data in this excel file will be imported into an Access database. The
19
11232
by: cj2 | last post by:
#1 Is there a quick way to export a datatable to an excel file? Or delimited file? #2 Where is the appropriate Microsoft monitored group to ask about writing reports in SQL Reporting services or SQL Server Business Intelligence Development Studio or whatever it's called?
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9997
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.