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

Export to Excel using VB.Net

, 25 Apr 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Export data from VB.Net Dataset to Excel without using Datagrid/DataTable

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)

Share

About the Author

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

Comments and Discussions

 
QuestionExcel PinmemberMember 1081187811-May-14 23:07 
QuestionThanks PinmemberKashif Alvi24-Aug-13 8:44 
QuestionThanks Pinmembernihadar12-Jun-13 22:57 
QuestionExport multiple DataSets to multiple Excel sheets using vb.net PinmemberPriyanka Jain3-May-13 23:40 
Questionhi PinmemberMember 999349622-Apr-13 15:34 
GeneralFree Export to Excel class, using OpenXML libraries PinmemberMike Gledhill1-Mar-13 7:54 
GeneralRe: Free Export to Excel class, using OpenXML libraries [modified] PinmemberMember 795657814-Mar-13 17:55 
Generalgood Pinmemberpootuba31-Jan-13 4:00 
QuestionError "Microsoft.Office.Interop.Excel" Pinmembermorteza_msh15-Jan-13 10:15 
AnswerRe: Error "Microsoft.Office.Interop.Excel" PinmemberDefilippo9-Dec-13 23:06 
QuestionExcel Chart in vb.net PinmemberOfir 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 Coding Pinmembervanchai hontong6-Dec-12 17:56 
QuestionThank you, very good example PinmemberMember 868754429-Oct-12 21:26 
GeneralMy vote of 5 PinmemberD-Kishore4-Sep-12 19:25 
GeneralMy vote of 5 PinmemberALDER_MORIGGI13-Jul-12 2:38 
GeneralMy vote of 5 PinmemberHimachandra5-Jul-12 23:06 
QuestionExporting DataGridView contents in an excel file following designed column format in an excel template 97-2003 PinmemberMember 898364524-May-12 22:32 
AnswerRe: Exporting DataGridView contents in an excel file following designed column format in an excel template 97-2003 PinmemberKurfuerstendamm19-Nov-13 0:25 
GeneralMy vote of 5 PinmemberMacParekh21-May-12 21:20 
GeneralMy vote of 5 PinmemberMember 432084410-Feb-12 4:52 
QuestionSeriously? Pinmemberortund5-Jan-12 20:57 
SuggestionAlternative way to export to a (genuine) Excel 2007 file, using OpenXML PinmemberMikeGledhill5-Dec-11 0:58 
GeneralMy vote of 5 PinmemberMember 815120624-Nov-11 2:55 
QuestionKeep getting error "A first chance exception of type 'System.NotImplementedException' occurred" PinmemberMember 833666720-Oct-11 11:22 
QuestionThans Senthil S Pinmemberdongcr10-Aug-11 22:54 
GeneralMy vote of 5 Pinmemberdongcr10-Aug-11 22:39 
QuestionExport only visible columns PinmemberMember 80141176-Jul-11 6:31 
GeneralMy vote of 4 PinmemberMember 80141176-Jul-11 6:29 
GeneralMy vote of 5 Pinmemberdeo cabral14-Jun-11 7:29 
GeneralRetrieve all the database table values to an excel PinmemberBhagya1112-Jun-11 22:56 
Generalyet another very nice excel export library Pinmemberaron.sinoai22-Apr-11 10:00 
Generali got error Pinmembersanhadenn9-Mar-11 20:10 
GeneralMy vote of 5 PinmemberMcGuire28-Feb-11 12:25 
GeneralGood way to do that, I have another way Pinmemberqgyn23-Feb-11 21:24 
Generalthanks Pinmemberekomahendro22-Feb-11 22:05 
GeneralMy vote of 5 Pinmembervvsbabji18-Jan-11 4:28 
Generalthanks Pinmemberjonesberyl17-Aug-10 22:15 
GeneralMy vote of 5 Pinmemberkumar_vk15-Aug-10 23:14 
GeneralMy vote of 5 Pinmembersankar07Ind15-Aug-10 23:10 
GeneralDataset takes too much time Pinmemberlbs.allies31-Mar-10 23:32 
GeneralRe: Dataset takes too much time PinmemberJamesHoward9726-Nov-11 22:50 
QuestionHow to export to excel 3 related tables into excel using vb.net Pinmemberyustock16-Mar-10 21:32 
GeneralError : inserted number value in to .xls file Pinmembermohankundenagoud10-Mar-10 23:34 
GeneralRe: Error : inserted number value in to .xls file PinmemberSenthil S11-Mar-10 10:59 
GeneralAlignment the column of excel PinmemberArul Soosai27-Jan-10 21:44 
GeneralThanks a lot Pinmembermalakrouhhi14-Dec-09 0:26 
Questionafter initial workbook.saveas I cannot move the xls to a new folder (locked) PinmemberALZDBA25-Sep-09 8:00 
GeneralThanks PinmemberMember 386212222-Sep-09 18:33 
QuestionHow i can export datagrid to existing excel file??? PinmemberB0nCelAja15-Sep-09 23:43 
AnswerRe: How i can export datagrid to existing excel file??? PinmemberCikaPero19-Feb-10 3:53 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 26 Apr 2008
Article Copyright 2007 by Senthil S
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid