Click here to Skip to main content
6,629,377 members and growing! (20,048 online)
Email Password   helpLost your password?
Languages » VB.NET » Applications     Beginner License: The Code Project Open License (CPOL)

Export to Excel using VB.Net

By Senthil S

Export data from VB.Net Dataset to Excel without using Datagrid/DataTable
VB 7.x, VB 8.0, VB 9.0, VB 6, .NET (.NET 2.0, .NET 3.0), Visual Studio (VS2005, VS2008), WinForms, Architect, Dev, QA
Posted:1 Aug 2007
Updated:25 Apr 2008
Views:152,064
Bookmarked:105 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
36 votes for this article.
Popularity: 5.76 Rating: 3.70 out of 5
2 votes, 5.6%
1
6 votes, 16.7%
2
1 vote, 2.8%
3
11 votes, 30.6%
4
16 votes, 44.4%
5

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


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

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 75 (Total in Forum: 75) (Refresh)FirstPrevNext
Questionafter initial workbook.saveas I cannot move the xls to a new folder (locked) PinmemberALZDBA9:00 25 Sep '09  
GeneralThanks PinmemberMember 386212219:33 22 Sep '09  
GeneralHow i can export datagrid to existing excel file??? PinmemberB0nCelAja0:43 16 Sep '09  
GeneralThanks Pinmemberavinashpatil3484new3:53 15 Sep '09  
Questionits helpful but...... PinmemberMember 13518501:29 29 Apr '09  
AnswerRe: its helpful but...... PinmemberFilipKrnjic5:17 9 Jul '09  
GeneralHow to delete data from X rows and Y columns in Excel using VB scrpits Pinmembervrajeshm0:31 27 Apr '09  
Generalhi PinmemberMember 44043093:48 13 Apr '09  
GeneralGreat Code PinmemberSargonis23:56 28 Mar '09  
GeneralThank You excellent PinmemberNazmiDUMAN9:54 19 Mar '09  
General[My vote of 2] Adding references PinmemberBonthula0:30 18 Mar '09  
QuestionProblem With Code!!!! - Please HELP - PinmemberMehdi Azizi10:50 12 Mar '09  
GeneralExcellent code Pinmemberjterc200015:27 24 Feb '09  
GeneralWhen I click on sln file to start - get error PinmemberMember 239668612:15 21 Jan '09  
Generalgetting a serious error Pinmembermanesti13:16 12 Jan '09  
GeneralRe: getting a serious error PinmemberSenthil S9:57 17 Jan '09  
GeneralRe: getting a serious error Pinmemberpriya_sarupri0:01 23 Mar '09  
GeneralRe: getting a serious error PinmemberSenthil S17:17 23 Mar '09  
GeneralRe: getting a serious error PinmemberMikMit10:12 1 Oct '09  
GeneralThank you PinmemberIndiana_Ken16:04 24 Dec '08  
GeneralRe: Thank you PinmemberSenthil S10:04 17 Jan '09  
GeneralMy vote of 2 Pinmemberrajthapliyal22:33 15 Dec '08  
GeneralRe: My vote of 2 PinmemberSenthil S10:02 17 Jan '09  
GeneralMy vote of 2 PinmemberWill77020:31 15 Dec '08  
GeneralRe: My vote of 2 Pinmembergg42371:51 5 Nov '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Apr 2008
Editor:
Copyright 2007 by Senthil S
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project