How to export from database to excel using VB.net

By: Issac Emailed: 1702 times Printed: 2203 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

In this article we can see how to export from database to excel. We can load the data from a database to dataset and then create a new Excel file and write the data into the Excel file. First step is to Load the Product table data to data set, next is to create a new Excel file and write the data from dataset to Excel file.

For i = 0 to ds.Tables (0).Rows.Count - 1
	For j = 0 to ds.Tables (0).Columns.Count - 1
		xlWorkSheet.Cells (i + 1, j + 1) = _
		ds.Tables (0).Rows (i).Item (j)
	Next
Imports System.Data
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        Dim cnn As SqlConnection
        Dim connectionString As String
        Dim sql As String
        Dim i, j As Integer

        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value

        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")

        connectionString = "data source=servername;" & _
        "initial catalog=databasename;user id=username;password=password;"
        cnn = New SqlConnection(connectionString)
        cnn.Open()
        sql = "SELECT * FROM Product"
        Dim dscmd As New SqlDataAdapter(sql, cnn)
        Dim ds As New DataSet
        dscmd.Fill(ds)

        For i = 0 To ds.Tables(0).Rows.Count - 1
            For j = 0 To ds.Tables(0).Columns.Count - 1
                xlWorkSheet.Cells(i + 1, j + 1) = _
                ds.Tables(0).Rows(i).Item(j)
            Next
        Next

        xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        cnn.Close()

        MsgBox("You can find the file C:\vbexcel.xlsx")
    End Sub

    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub
End Class

VB.net Home | All VB.net Tutorials | Latest VB.net Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(5)


1. View Comment

I was trying to copy your coding and execute it, but no data was extracted out in excel.
(FYI - i've replaced the sql query to extract the data from my database). Any thought? Thanks


View Tutorial          By: Guest at 2012-01-02 04:08:21
2. View Comment

Your script works beautifully. Is there a way to include the header on the first row of the worksheet?

Thank you in advance.


View Tutorial          By: JW at 2013-05-08 22:22:44
3. View Comment

you do the same as after
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As SqlConnection
Dim sql As String
Dim i, j As Integer

Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
cnn = Connection.getConnection()
cnn.Open()
sql = "SELECT * FROM tblNVcanhan"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
For i = 0 To ds.Tables(0).Columns.Count - 1
xlWorkSheet.Cells(1, i + 1) = ds.Tables(0).Columns(i).ToString()
Next
For j = 0 To ds.Tables(0).Rows.Count - 1
xlWorkSheet.Cells(j + 2, 1) = ds.Tables(0).Columns(j).ToString()
For i = 0 To ds.Tables(0).Columns.Count - 1
xlWorkSheet.Cells(j + 2, i + 1) = ds.Tables(0).Rows(j).Item(i).ToString()
Next
Next
xlApp.Columns.AutoFit()
'xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
'xlWorkBook.Close()
MsgBox("You can find the file D:\vbexcel.xlsx")
xlApp.Visible = True

releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)

cnn.Close()

End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub


View Tutorial          By: John McCode at 2013-05-24 07:57:31
4. View Comment

Thanks For uploading , Can you please guide , How can i create multiple excel sheet on single button event in VB.net

View Tutorial          By: Manish Choudhari at 2014-10-14 09:58:05
5. View Comment

Hello
thanks for nice tutorial. I have one application, installed on client machine . when i try to export data to excel it just give a error of exporting . actually my client pc dont have excel installed on machine so what should i do get over from it .


View Tutorial          By: Chanchal Prajapat at 2015-02-09 06:10:42

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Issac
Save/Write/Read image file from/to a database using Java program
How to modify the objects using java classes
Java program for Cloning
Java program for changeable wrapper class
A tutorial on Chat Server and Chat Client in VB.net
Chat Server in VB.net
Chat client in VB.net
How to open and read an XML file in VB.net
How to create an XML file in VB.net
XML and VB.net
How to create an XML file in VB.NET using Dataset
Multi Threaded Client Socket Programming in VB.net
Multi Threaded Server Socket Programming in VB.net
Multi threaded Socket Programming in VB.net
Client Socket Program sample in VB.net

More Tutorials in VB.net
Scope in VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Creating Functions in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Procedure Delegates in VB.net
Properties in VB.net
Understanding Scope in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Getting an Exception's Number and Description in VB.net
Raising an Exception Intentionally in VB.net

More Latest News
Most Viewed Articles (in VB.net )
Nested If and Single line if statement
What is .NET Framework and the Common Language Runtime?
Visual Basic Statements
Sub Procedures and Functions in VB.net
String Insert, index off & format in VB.net
String.Contains (), compare, clone in VB.net
Vb.net binary reader and writer
Using Excel 2007 Chart in VB.NET 2005
Update cell data in an Excel file using OLEDB in VB.net
How to export from database to excel using VB.net
Client Socket Program sample in VB.net
Chat client in VB.net
Creating Tree Views in Code using VB.net
Creating List Views in Code using VB.net
Throwing a Custom Exception in VB.net
Most Emailed Articles (in VB.net)
How to export from database to excel using VB.net
Changes in Controls from VB6 to VB.net
What is .NET Framework and the Common Language Runtime?
While Loop in VB.net
Substring in Vb.Net String Class
Create an Excel 2007 file in VB.NET 2005
Insert Pictures in Excel 2007 from VB.NET 2005
Socket Programming in VB.net
Chat Server in VB.net
Using the ServiceBase Class in VB.net
Using Select Case in VB.net
String Insert, index off & format in VB.net
String Split function in VB.net
Vb.net text reader
Format Excel 2007 Page in VB.NET