Click here to Skip to main content
Click here to Skip to main content

Export to Excel using VB.Net

By , 25 Apr 2008
 

image2.JPG

Introduction

Export the data's to Excel of Microsoft office is currently need in many concern. But many of them used very complicated coding for simple export either from Datagrid or DataTable. I used simple Dataset to export the data.

Background

Introducing the way of sending data's from datagrid or by Datatable. I used Dataset which is easy to use. But for code optimization dataset is not advisable compare to Reader and DataTable

Using the code

In current available code for export the data to Excel are given. Which are so completed and not in straight forward. Because they used the Datagrid and DataTable. Which are given below.

From DataTable to Excel sheet,

          Dim dt1 As New DataTable
          Dim I1, J1 As Integer
          For I1 = 0 To dsmas1.Tables(0).Columns.Count - 1
                dt1.Columns.Add(dsmas1.Tables(0).Columns(I1).ColumnName)
           Next
           For I1 = 0 To dsmas1.Tables(0).Rows.Count - 1
                Dim DR As DataRow = Nothing
                DR = dt1.NewRow
                For J1 = 0 To dsmas1.Tables(0).Columns.Count - 1
                    DR.Item(J1) = dsmas1.Tables(0).Rows(I1).ItemArray(J1)
                Next
                dt1.Rows.Add(DR)
           Next
           rel_ds.Tables.Add(dt1)
           Dim dt As New DataTable
           Dim I, J As Integer
           For I = 0 To dschd1.Tables(0).Columns.Count - 1
                dt.Columns.Add(dschd1.Tables(0).Columns(I).ColumnName)
           Next
           For I = 0 To dschd1.Tables(0).Rows.Count - 1
                Dim DR As DataRow = Nothing
                DR = dt.NewRow
                For J = 0 To dschd1.Tables(0).Columns.Count - 1
                    DR.Item(J) = dschd1.Tables(0).Rows(I).ItemArray(J)
                Next
                dt.Rows.Add(DR)
           Next
            rel_ds.Tables.Add(dt)
 

For DataGrid to Excel sheet

        'verfying the datagridview having data or not
        If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
            Exit Sub
        End If

        'Creating dataset to export
        Dim dset As New DataSet
        'add table to dataset
        dset.Tables.Add()
        'add column to that table
        For i As Integer = 0 To DataGridView1.ColumnCount - 1
            dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
        Next
        'add rows to the table
        Dim dr1 As DataRow
        For i As Integer = 0 To DataGridView1.RowCount - 1
            dr1 = dset.Tables(0).NewRow
            For j As Integer = 0 To DataGridView1.Columns.Count - 1
                dr1(j) = DataGridView1.Rows(i).Cells(j).Value
            Next
            dset.Tables(0).Rows.Add(dr1)
        Next

        Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
        Dim wBook As Microsoft.Office.Interop.Excel.Workbook
        Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

        wBook = excel.Workbooks.Add()
        wSheet = wBook.ActiveSheet()

        Dim dt As System.Data.DataTable = dset.Tables(0)
        Dim dc As System.Data.DataColumn
        Dim dr As System.Data.DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0

        For Each dc In dt.Columns
            colIndex = colIndex + 1
            excel.Cells(1, colIndex) = dc.ColumnName
        Next

        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
                excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)

            Next
        Next

        wSheet.Columns.AutoFit()
        Dim strFileName As String = "D:\ss.xls"
        Dim blnFileOpen As Boolean = False
        Try
            Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
            fileTemp.Close()
        Catch ex As Exception
            blnFileOpen = False
        End Try

        If System.IO.File.Exists(strFileName) Then
            System.IO.File.Delete(strFileName)
        End If

        wBook.SaveAs(strFileName)
        excel.Workbooks.Open(strFileName)
        excel.Visible = True 

But i used only Dataset to Excel sheet

In code, I used a user defined function called "Load_Excel_Details()" which i used old technique like create Object for Excel, add the Book for a sheet and sheet for the data.

i.e,.

  • Excel <-- System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
    • Book <------ Excel Workbooks.Add()
      • Sheet <----- Excel SheetsInNewWorkbook = 1
        • Data <----- Excel cells(1, i).value

Which is used in the code like given below:

 With Excel
       .SheetsInNewWorkbook = 1
       .Workbooks.Add()
       .Worksheets(1).Select()

      Dim i As Integer = 1
      For col = 0 To ComDset.Tables(0).Columns.Count - 1
           .cells(1, i).value = ComDset.Tables(0).Columns(col).ColumnName
           .cells(1, i).EntireRow.Font.Bold = True
           i += 1
      Next

            i = 2

       Dim k As Integer = 1
       For col = 0 To ComDset.Tables(0).Columns.Count - 1
          i = 2
          For row = 0 To ComDset.Tables(0).Rows.Count - 1
              .Cells(i, k).Value = ComDset.Tables(0).Rows(row).ItemArray(col)
               i += 1
          Next
               k += 1
       Next
          filename = "c:\File_Exported.xls"
         .ActiveCell.Worksheet.SaveAs(filename)
 End With

Points of Interest

I used simple For loops.... and insert the values by Rows, Columns and Cells formats.

History

I proposed this after i used in my company project which appreciate by the customers.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Senthil S
Software Developer
India India
Member
Hello,
This is Senthil.S. I am a Software Engineer at TCS. I am Currently Standing on .Net and Flex Platform.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionExport multiple DataSets to multiple Excel sheets using vb.netmemberPriyanka Jain3 May '13 - 23:40 
Hello sir,
Your Code is working Properly but I have three data Set, I want to export the data from one dataset to one sheet and respectively.how i can achieve that?
please help me..
Priyanka Jain

QuestionhimemberMember 999349622 Apr '13 - 15:34 
can i ask if you know about .sdf files. its for databases
GeneralFree Export to Excel class, using OpenXML librariesmemberMike Gledhill1 Mar '13 - 7:54 
I've also been busy, writing an "Export to Excel" class for C# and VB.Net.
 
It lets you export a DataSet, DataTable or List<> into a real Excel 2007/10 .xlsx file, with just one line of code. And because it's based on Microsoft's free OpenXML libraries, you don't need to have Excel installed on your server.
 
You can download the full source code, plus a demo, from the following site.
No registration/login required !
 
http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm[^]
 

Mike
GeneralRe: Free Export to Excel class, using OpenXML libraries [modified]memberMember 795657814 Mar '13 - 17:55 
dear mike,
thanks for your sharing on link above. but i am using visual studio 2008 (vb.net), so i can't open properly your sample and i rewrite your code.
after running, the output (file excel can be created) but when its open error message will occured.
"excel found unreadable content in Sample.xlsx;. Do you want to recover the contents of this
workbook?
"
thus, when i press ok, the file will be opened with blank data
please help me to avoid this trouble :(

modified 15 Mar '13 - 3:36.

Generalgoodmemberpootuba31 Jan '13 - 4:00 
i love youThumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
QuestionError "Microsoft.Office.Interop.Excel"membermorteza_msh15 Jan '13 - 10:15 
i'm using vb.net 2010, when i compiled your project, error message shown below
Error message --> Type 'Microsoft.Office.Interop.Excel.Workbook' and 'Microsoft.Office.Interop.Excel.ApplicationClass' and 'Microsoft.Office.Interop.Excel.Worksheet is not defined.
how to solve this error?
thanks
QuestionExcel Chart in vb.netmemberOfir G.20 Dec '12 - 2:03 
hello
i made an excel chart in vb.net successfully.
i have a problem with moving the X axis to the bottom of the chart.
in vb6 it is done like that:
chart.Axes(xlCategory, xlPrimary).TickLabelPosition = xlLow
how it is done in vb.net ?
thanks
GeneralThank you Your Codingmembervanchai hontong6 Dec '12 - 17:56 
Your Coding Step is very good.
 
vinny, thailand
QuestionThank you, very good examplememberMember 868754429 Oct '12 - 21:26 
Thank you, very good example
GeneralMy vote of 5memberD-Kishore4 Sep '12 - 19:25 
good
GeneralMy vote of 5memberALDER_MORIGGI13 Jul '12 - 2:38 
Thank you, very good example!
GeneralMy vote of 5memberHimachandra5 Jul '12 - 23:06 
Its working fine and its in understandable mode.....
QuestionExporting DataGridView contents in an excel file following designed column format in an excel template 97-2003memberMember 898364524 May '12 - 22:32 
Hi Good day!
 
I want to ask "How can I export a data coming from gridview that allows me to follow the format i made in an excel template file.
 
Please help...
 
Thank you in advance..Smile | :)
GeneralMy vote of 5memberMacParekh21 May '12 - 21:20 
Thanks
GeneralMy vote of 5memberMember 432084410 Feb '12 - 4:52 
Very Good.
QuestionSeriously?memberortund5 Jan '12 - 20:57 
Why did you use Comic Sans on your buttons?
SuggestionAlternative way to export to a (genuine) Excel 2007 file, using OpenXMLmemberMikeGledhill5 Dec '11 - 0:58 
Have a look at the following webpage.
 
It shows you how to export from a DataTable, DataSet or List<> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries.
 
After adding the class to your application, you can Export using just one function call:
 
DataSet ds = CreateSampleData();
CreateExcelFile.CreateExcelDocument(ds, "C:\\Sample.xlsx");
 
All the source code is provided, along with a demo application, but it's all in C#.Net, rather than VB.Net.
 
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm[^]
 
Good luck...
GeneralMy vote of 5memberMember 815120624 Nov '11 - 2:55 
ok
QuestionKeep getting error "A first chance exception of type 'System.NotImplementedException' occurred"memberMember 833666720 Oct '11 - 11:22 
Hi,
 
I implemented the below code to export data from a data grid to excel. The code compiles correctly but I get an error message "A first chance exception of type 'System.NotImplementedException' occurred" when I click on the button to export data to excel.
 
I am working on the trial version of Visual Studio 2010 and currently have a licensed copy of Office 2007 installed on my machine. "Microsoft.Office.Interop.Excel" reference has been correctly imported.
 
Appreciate if someone can provide some insight into thisi ssue.
 
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        'verfying the datagridview having data or not
        If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
            Exit Sub
        End If
 
        'Creating dataset to export
        Dim dset As New DataSet
        'add table to dataset
        dset.Tables.Add()
        'add column to that table
        For i As Integer = 0 To DataGridView1.ColumnCount - 1
            dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
        Next
        'add rows to the table
        Dim dr1 As DataRow
        For i As Integer = 0 To DataGridView1.RowCount - 1
            dr1 = dset.Tables(0).NewRow
            For j As Integer = 0 To DataGridView1.Columns.Count - 1
                dr1(j) = DataGridView1.Rows(i).Cells(j).Value
            Next
            dset.Tables(0).Rows.Add(dr1)
        Next
 
        Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
        Dim wBook As Microsoft.Office.Interop.Excel.Workbook
        Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
 
        wBook = excel.Workbooks.Add()
        wSheet = wBook.ActiveSheet()
 
        Dim dt As System.Data.DataTable = dset.Tables(0)
        Dim dc As System.Data.DataColumn
        Dim dr As System.Data.DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0
 
        For Each dc In dt.Columns
            colIndex = colIndex + 1
            excel.Cells(1, colIndex) = dc.ColumnName
        Next
 
        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
                excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
 
            Next
        Next
 
        wSheet.Columns.AutoFit()
        Dim strFileName As String = "C:\ss.xls"
        Dim blnFileOpen As Boolean = False
        Try
            Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
            fileTemp.Close()
        Catch ex As Exception
            blnFileOpen = False
        End Try
 
        If System.IO.File.Exists(strFileName) Then
            System.IO.File.Delete(strFileName)
        End If
 
        wBook.SaveAs(strFileName)
        excel.Workbooks.Open(strFileName)
        excel.Visible = True
    End Sub

QuestionThans Senthil Smemberdongcr10 Aug '11 - 22:54 
Thanks Senthil S have give code Export to excel vb.net.
This code help me finish my project.
Thanh you very much.
GeneralMy vote of 5memberdongcr10 Aug '11 - 22:39 
this subject of Senthil S very good and useful
QuestionExport only visible columnsmemberMember 80141176 Jul '11 - 6:31 
Hello.
 
This is an excellente piece of code and helped me a lot.
Can someone please show me how to change it in order to export only visible columns?
 
Thanks in advance
Octavio.
GeneralMy vote of 4memberMember 80141176 Jul '11 - 6:29 
Good article. Just need to know how to export only visible columns
GeneralMy vote of 5memberdeo cabral14 Jun '11 - 7:29 
simple and efficient

modified on Wednesday, June 15, 2011 11:48 AM

GeneralRetrieve all the database table values to an excelmemberBhagya1112 Jun '11 - 22:56 
hi Senthil,
 
I need to creat a tool in macro to "Retrieve all the database table values to an excel"
i wil wexplain u the scenario on whole:
Steps are:
1)Create Dsn
2)Retrieve data from database
3)Inserting into excel.
 
Procedure:
In the sheet1 of excel we wil be having 4 labels as Dsn name,username,password,database table name and a button.
Once i click on this button,all the content in the database table should be available in sheet2.
Could u plz hep me on dis with the vbscript code.
 
Thanks in advance,
Bhagya

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 26 Apr 2008
Article Copyright 2007 by Senthil S
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid