Click here to Skip to main content
6,293,171 members and growing! (12,370 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Exporting a Dataset with multiple tables in separate sheets in an Excel file

By jain.ashish21

This article describes how to export the data from multiple tables in a Dataset to an Excel file in separate sheets.
VB, C# 1.0, Windows, .NET 1.1, ASP.NET, WebForms, VS.NET2003, Dev
Posted:23 May 2007
Views:39,301
Bookmarked:35 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
3 votes for this article.
Popularity: 1.43 Rating: 3.00 out of 5
1 vote, 33.3%
1

2
1 vote, 33.3%
3

4
1 vote, 33.3%
5

Introduction

This article explains how to export the contents of a Dataset with more than one table, to an excel workbook in separate sheets. The article also helps understand the basics behind the Excel application object and its usage for creating a Workbook and inserting Worksheets in it. The following code can however extend its functionalities by incorporating methods and procedures for formatting the written data like the cell background, font color, inserting formulas etc.

Background

The need to write this code came up when one of my applications needed the same functionalities where my stored procedure returned two result sets which I stored in a Dataset. The user wanted the two result sets to be displayed in two separate sheets in an excel file. But the current method of Response.AddHeader ("content-disposition") allowed me to write the output in one single sheet with the two result sets one below the other. After exploring the net and integration of a couple of techniques, I came up with a solution which could solve my purpose of creating an excel file and then writing the data from the dataset tables in the excel file.

Using the Code - Implementation

The code is pretty simple and straight forward. As a pre-requisite you should have Excel installed on your system. I have used VB.Net as my base language. Although with a little modification you can always convert the existing code in C# too.

In order to start using the code, add a reference to the COM object Microsoft Excel Object Library. Since I had Microsoft Office 2003 installed on my system, it was Microsoft Excel 11.0 Object Library in my case. Now import the namespaces for the Excel library and InterpServices into your code

Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices.Marshal

We will need to import the InteropServices because the Microsoft Office code is still based in the old, unmanaged world and you need to use COM Interop to facilitate communication with it. Now copy the following code to your Code behind file to export the dataset tables to excel. The function takes as parameter a DataSet containing the DataTables

Public Sub ExportToExcel(ByVal DS_MyDataset As DataSet)

    //The full path where the excel file will be stored

    Dim strFileName As String = AppDomain.CurrentDomain.BaseDirectory.Replace("/", "\") 
    strFileName = strFileName & "\MyExcelFile" & System.DateTime.Now.Ticks.ToString() ".xls"

    Dim objExcel As Excel.Application
    Dim objBooks As Excel.Workbooks, objBook As Excel.Workbook
    Dim objSheets As Excel.Sheets, objSheet As Excel.Worksheet
    Dim objRange As Excel.Range

    Try
        //Creating a new object of the Excel application object
        objExcel = New Excel.Application
        //Hiding the Excel application
        objExcel.Visible = False
        //Hiding all the alert messages occurring during the process
        objExcel.DisplayAlerts = False

        //Adding a collection of Workbooks to the Excel object
        objBook = CType(objExcel.Workbooks.Add(), Excel. Workbook)

        //Saving the Workbook as a normal workbook format.
        objBook.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal) 

        //Getting the collection of workbooks in an object
        objBooks = objExcel.Workbooks

        //Get the reference to the first sheet in the workbook collection in a variable
        objSheet = CType(objBooks(1).objSheets.Item(1), Excel.Worksheet)
        //Optionally name the worksheet
        objSheet.Name = "First Sheet"
        //You can even set the font attributes of a range of cells in the sheet. Here we have set the fonts to bold.
        objSheet.Range("A1","Z1").Font.Bold = True 

        //Get the cells collection of the sheet in a variable, to write the data.
        objRange = objSheet.Cells

        //Calling the function to write the dataset data in the cells of the first sheet.
        WriteData(DS_MyDataset.Tables(0), objCells)

        //Setting the width of the specified range of cells so as to absolutely fit the written data.
        objSheet.Range("A1","Z1").EntireColumn.AutoFit()
        //Saving the worksheet.
        objSheet.SaveAs(strFileName)
        
        objBook = objBooks.Item(1)
        objSheets = objBook.Worksheets
        objSheet = CType(objSheets.Item(2), Excel.Worksheet)
        objSheet.Name = "Second Sheet"
        //Setting the color of the specified range of cells to Red (ColorIndex 3 denoted Red color)
        objSheet.Range("A1","Z1").Font.ColorIndex = 3

        objRange = objSheet.Cells
        WriteData(DS_MyDataset.Tables(1), objCells)
        objSheet.Range("A1","Z1").EntireColumn.AutoFit()

        objSheet.SaveAs(strFileName)

    Catch ex As Exception
        Response.Write(ex.Message)
    Finally
        //Close the Excel application
        objExcel.Quit()

        //Release all the COM objects so as to free the memory
        ReleaseComObject(objRange)
        ReleaseComObject(objSheet)
        ReleaseComObject(objSheets)
        ReleaseComObject(objBook)
        ReleaseComObject(objBooks)
        ReleaseComObject(objExcel)

        //Set the all the objects for the Garbage collector to collect them.
        objExcel = Nothing 
        objBooks = Nothing 
        objBook = Nothing 
        objSheets = Nothing 
        objSheet = Nothing 
        objRange = Nothing 

        //Specifically call the garbage collector.
        System.GC.Collect()
    End Try
End Sub

Private Function WriteData(ByVal DT_DataTable As DataTable, ByVal objCells As Excel.Range) As String
    Dim iRow As Integer, iCol As Integer

    //Traverse through the DataTable columns to write the headers on the first row of the excel sheet.
    For iCol = 0 To DT_DataTable.Columns.Count - 1
        objCells(1, iCol + 1) = DT_DataTable.Columns(iCol).ToString
    Next

    //Traverse through the rows and columns of the datatable to write the data in the sheet.
    For iRow = 0 To DT_DataTable.Rows.Count - 1
        For iCol = 0 To DT_DataTable.Columns.Count - 1
            objCells(iRow + 2, iCol + 1) = DT_DataTable.Rows(iRow)(iCol)
        Next
    Next
End Function

Pros and Cons

Pros:

  • Code can be used as a component to export formatted reports to excel.
  • The code is very small and can be modified as per the user requirements for getting formatted output on excel sheets in a presentable format.

Cons:

  • The code uses Excel Object library which is required at the development server.
  • Since the code creates objects of the COM components through Interop services, if the components are not efficiently released, may result in memory leakage.

Conclusion

You can see that the above code is self explanatory and quite understandable. The code can further be enhanced by formatting the written data like the background of the cells, adding gridlines to the excel sheet etc. We can even add more sheets to the file if the dataset contains more than 3 tables since the default workbook has 3 sheets. The above code is just a sample of what all can be done with the excel object. A more enhanced exception handling can be done by catching more specific exceptions. Enjoy and happy coding!!!!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

jain.ashish21


Member

Occupation: Web Developer
Location: India India

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 17 of 17 (Total in Forum: 17) (Refresh)FirstPrevNext
GeneralMy vote of 1 Pinmembervannavada8:48 3 Feb '09  
GeneralGetting error while adding Worksheet PinmemberMark_20004:36 6 Jun '08  
QuestionGot object reference Error Pinmemberprakashkpd22:22 3 Oct '07  
GeneralExporting Excel pivot charts in ASP.NET 1.1 Aplication? Pinmemberk_bhawna20:01 1 Jun '07  
GeneralAvoiding the need for Excel on the server Pinmemberpurplepangolin0:55 24 May '07  
GeneralRe: Avoiding the need for Excel on the server Pinmemberjain.ashish211:20 24 May '07  
GeneralRe: Avoiding the need for Excel on the server Pinmemberpurplepangolin1:39 24 May '07  
QuestionRe: Avoiding the need for Excel on the server Pinmemberjain.ashish2123:16 24 May '07  
AnswerRe: Avoiding the need for Excel on the server Pinmemberpurplepangolin23:39 24 May '07  
QuestionRe: Avoiding the need for Excel on the server Pinmemberjain.ashish2123:44 24 May '07  
AnswerRe: Avoiding the need for Excel on the server Pinmemberpurplepangolin23:50 24 May '07  
QuestionRe: Avoiding the need for Excel on the server Pinmemberjain.ashish210:06 25 May '07  
AnswerRe: Avoiding the need for Excel on the server Pinmemberpurplepangolin0:11 25 May '07  
GeneralRe: Avoiding the need for Excel on the server Pinmemberramki_mars22:18 22 Jul '08  
AnswerRe: Avoiding the need for Excel on the server Pinmemberminga484:18 23 Sep '08  
AnswerRe: Avoiding the need for Excel on the server PinmemberJrgen Andersson1:38 30 May '07  
GeneralRe: Avoiding the need for Excel on the server Pinmemberramki_mars22:21 22 Jul '08  

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

PermaLink | Privacy | Terms of Use
Last Updated: 23 May 2007
Editor:
Copyright 2007 by jain.ashish21
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project