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: - Imports System.Runtime.InteropServices.Marshal
Now add the following class to your project: - 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
To generate the individual sheets, the following Sub is used: - Private Sub GenerateExcelFile(ByRef table As DataTable, ByVal xlCells As Excel.Range)
-
Dim dr As DataRow, ary() As Object
-
Dim iRow As Integer, iCol As Integer
-
'Output Column Headers
-
For iCol = 0 To table.Columns.Count - 1
-
xlCells(1, iCol + 1) = table.Columns(iCol).ToString
-
xlCells(1).EntireRow.Font.Bold = True
-
Next
-
'Output Data
-
For iRow = 0 To table.Rows.Count - 1
-
dr = table.Rows.Item(iRow)
-
ary = dr.ItemArray
-
For iCol = 0 To UBound(ary)
-
xlCells(iRow + 2, iCol + 1) = ary(iCol).ToString
-
Response.Write(ary(iCol).ToString & vbTab)
-
Next
-
Next
-
xlCells.Columns.AutoFit()
-
End Sub
And now the trick to getting all tables and data from a database: - Public database as String
-
Public ReadOnly Property getAllTables(ByVal sDB As String) As DataSet
-
Get
-
database = sDB
-
Dim m_dshelp As DataSet = New DataSet
-
getRequestedAllTables(m_dshelp)
-
Return m_dshelp
-
End Get
-
End Property
-
-
Private Function getRequestedAllTables(ByRef p_dataset As DataSet) As Boolean
-
'Retrieve all tablenames from the database:
-
Dim sSQL As String
-
Dim dsTables As DataSet = New DataSet
-
sSQL = "SELECT [TableName] = so.name, [RowCount] = MAX(si.rows) " & _
-
"FROM sysobjects so, sysindexes si " & _
-
"WHERE so.xtype = 'U' AND si.id = OBJECT_ID(so.name) AND si.rows > 0 " & _
-
"GROUP BY so.name " & _
-
"ORDER BY 2 DESC"
-
getData(sSQL, "Tables", dsTables)
-
'Loop thrue all tables and do a SELECT *. Then add them to the dataset
-
For i As Integer = 0 To dsTables.Tables(0).Rows.Count - 1
-
sSQL = "SELECT * FROM " & dsTables.Tables(0).Rows(i).Item(0)
-
getData(sSQL, dsTables.Tables(0).Rows(i).Item(0), p_dataset)
-
Next
-
End Function
-
-
Private Function getData(ByVal p_sql As String, ByVal p_table As String, ByRef pdataset As DataSet) As Boolean
-
Dim objDataAdapter As SqlDataAdapter
-
Dim objcommand As SqlCommand
-
objcommand = New SqlCommand(p_sql, getConnection)
-
objDataAdapter = New SqlDataAdapter(objcommand)
-
objDataAdapter.Fill(pdataset, p_table)
-
End Function
-
-
Private Function getConnection() As SqlConnection
-
If (ConfigurationManager.AppSettings("SQLPW") <> "") Then
-
getConnection = New SqlConnection("Server=" & _
-
ConfigurationManager.AppSettings("SQLserver") & ";password=" & _
-
ConfigurationManager.AppSettings("SQLPW") & "; user=" & _
-
ConfigurationManager.AppSettings("SQLUser") & ";database=" & database)
-
Else
-
getConnection = New SqlConnection("Data Source=" & _
-
ConfigurationManager.AppSettings("SQLserver") & ";Initial Catalog=" & _
-
database & ";Integrated Security=True")
-
End If
-
End Function
That's all there is to it!! Happy Coding!
1 6690
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!
Sign in to post your reply or Sign up for a free account.
Similar topics |
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.
|
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...
|
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...
|
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:
|
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...
| |
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...
|
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...
|
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
|
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?
|
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...
|
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,...
| |
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...
|
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...
|
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...
|
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();...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |