Click here to Skip to main content
15,891,033 members
Articles / Desktop Programming / Windows Forms

Export to Excel using VB.NET

Rate me:
Please Sign up or sign in to vote.
4.46/5 (75 votes)
25 Apr 2008CPOL1 min read 1M   36K   172   132
Export data from VB.NET Dataset to Excel without using Datagrid/DataTable

Senthil_S__Software_Eng_/image2.jpg

Introduction

Exporting data to Excel of Microsoft Office is currently needed. 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 from datagrid or by Datatable. I used Dataset which is easy to use. But for code optimization, dataset is not advisable compared to Reader and DataTable.

Using the Code

Currently, available code for exporting the data to Excel are given which is so complete and not straight forward because they used the Datagrid and DataTable which are given below:

From DataTable to Excel sheet:

VB.NET
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:

VB.NET
'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()" in which I used an 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:

VB.NET
 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 it in my company project which was appreciate by the customers.

License

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


Written By
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

 
GeneralFine but have doubt Pin
kasimmohamed21-Oct-08 0:55
kasimmohamed21-Oct-08 0:55 
GeneralRe: Fine but have doubt Pin
Senthil S24-Oct-08 23:29
Senthil S24-Oct-08 23:29 
GeneralFurther Help Sir Senthil S Pin
jacebeleren2-Oct-08 22:53
jacebeleren2-Oct-08 22:53 
QuestionHello experts: Problems writing SQL code for Excell workBOOK please help me Pin
sivi0071-Oct-08 5:39
sivi0071-Oct-08 5:39 
Generalhelp Pin
priyajeni15-Sep-08 18:54
priyajeni15-Sep-08 18:54 
Generalpls help me out senthil Pin
shalu.mathews13-Sep-08 17:58
shalu.mathews13-Sep-08 17:58 
Question3 errors occured [modified] Pin
shalu.mathews13-Sep-08 6:03
shalu.mathews13-Sep-08 6:03 
GeneralCode not working at my end Pin
bkukki15-Aug-08 3:19
bkukki15-Aug-08 3:19 
hi senthil:

i have a datagridview which needs to be transferred to an excel spreadsheet. I use VS 2005 and ms access 2003(db) and excel 2003. I dont get any errors but i dont see the excel created;.. Frown | :( i also have another qn.. i have a few results colored in my datagridview.. how do i make it colored even in my excel spreadsheet ??

I would really appreciate ur help..Expecting a reply at the earliest.. I am sorry but I have been stuck on this for 2 weeks now..! Frown | :(

Thanks Senthil

Kavitha.





Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then

            Exit Sub

        End If

        Dim dset As New DataSet

        dset.Tables.Add()

        For i As Integer = 0 To DataGridView1.ColumnCount - 1

            dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)

        Next

        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.Application

        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:\Documents and Settings\bashkark\Desktop\MCAD.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

        wbook.SaveAs(strfilename)

        excel.Workbooks.Open(strfilename)

        excel.Visible = True

        MsgBox("created")

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click   'This button is for navigating from Form3 to Form2

        Dim formtoshow As New Form2

        formtoshow.Show()

        Me.Dispose()


    End Sub

GeneralFinally..Thank You Senthil Pin
henry_yacob13-Aug-08 17:52
henry_yacob13-Aug-08 17:52 
GeneralExport Datagridview data to Excel Pin
giverofjoy9-Aug-08 1:22
giverofjoy9-Aug-08 1:22 
GeneralRe: Export Datagridview data to Excel Pin
Senthil S14-Aug-08 14:28
Senthil S14-Aug-08 14:28 
Generalhelp with error Pin
Norminator7-Aug-08 10:53
Norminator7-Aug-08 10:53 
Generalerror Old format or invalid type library. Pin
cheehongjb31-Jul-08 17:58
cheehongjb31-Jul-08 17:58 
GeneralRe: error Old format or invalid type library. Pin
Senthil S14-Aug-08 14:24
Senthil S14-Aug-08 14:24 
GeneralRe: error Old format or invalid type library. Pin
Member 382269826-Aug-08 1:32
Member 382269826-Aug-08 1:32 
GeneralRe: error Old format or invalid type library. Pin
Senthil S27-Aug-08 14:43
Senthil S27-Aug-08 14:43 
GeneralHelp with Type Error Pin
cgillespie24-Jun-08 7:35
cgillespie24-Jun-08 7:35 
GeneralRe: Help with Type Error Pin
alexi0729-Jun-08 23:44
alexi0729-Jun-08 23:44 
GeneralRe: Help with Type Error Pin
cgillespie30-Jun-08 10:41
cgillespie30-Jun-08 10:41 
GeneralRe: Help with Type Error Pin
Senthil S30-Jun-08 17:01
Senthil S30-Jun-08 17:01 
GeneralSenthil Good JOB Pin
giribabu2349-Jun-08 2:24
giribabu2349-Jun-08 2:24 
GeneralRe: Senthil Good JOB Pin
Senthil S9-Jun-08 18:58
Senthil S9-Jun-08 18:58 
QuestionPLS HELP Pin
safealloys7-Jun-08 10:04
safealloys7-Jun-08 10:04 
AnswerRe: PLS HELP Pin
Senthil S7-Jun-08 17:00
Senthil S7-Jun-08 17:00 
AnswerRe: PLS HELP Pin
dineshsirohi25-Sep-08 1:57
dineshsirohi25-Sep-08 1:57 

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

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