Click here to Skip to main content
6,595,444 members and growing! (15,378 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

C# class library for exporting data to CSV/Excel file

By Rama Krishna Kolluri

Free source code and tutorials for exporting data to CSV/Excel file from Web/Win Forms
C#, VB, Windows, .NET 1.1, ASP.NET, WebForms, VS.NET2003, Dev
Posted:29 Sep 2004
Updated:12 Apr 2007
Views:508,388
Bookmarked:256 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
127 votes for this article.
Popularity: 8.83 Rating: 4.20 out of 5
9 votes, 7.2%
1
6 votes, 4.8%
2
7 votes, 5.6%
3
31 votes, 24.8%
4
72 votes, 57.6%
5

Screenshot - ExportCode_ScreenShot.jpg

Introduction

Exporting data from a datatable to Excel or CSV is one of the most common functionality required in ASP.NET pages. Users can download the data from the datagrid into an Excel spreadsheet or CSV file for offline verification and/or computation. This article includes the source code for such functionality.

The common problems in exporting data from datagrid are

  1. To clean up the formatting and export data only.
  2. The header row in Excel always contained the database column names which were sometimes unintelligible to an ordinary user.
  3. Often the Datasets contain data, like Internal Reference ID, necessary for the datagrid generation, which we didn't want the end user to see.

To remedy all these issues I came up with the a simpler and more adaptable way to export the datagrid itself to Excel or CSV file.

I kept the concept to a dll so that it could easily be used throughout an application.

Using the ExportData class library

This class library is fully implemented in C#.NET. This dll doesn't need to be registered. Simply copy the assembly "RKLib.ExportData.dll" into your project folder and add it to references. You can also include the "ExportData" project and reference it in your project.

This can be used in WebForms as well as in WinForms by simply passing a parameter to the export object's constructor.

  • For WebForms:
    RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Web")
  • For WinForms:
    RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win")

The ExportDetails method has three types of overloads. You can call whichever best suits your requirement.

The following are the overload types:

  • public void ExportDetails(DataTable DetailsTable, 
      ExportFormat FormatType, string FileName)
  • public void ExportDetails(DataTable DetailsTable, int[] 
      ColumnList, ExportFormat FormatType, string FileName)
  • public void ExportDetails(DataTable DetailsTable, int[] 
      ColumnList, string[] Headers, ExportFormat FormatType, string FileName)

Have a glance at the parameters

  • DetailsTable - DataTable to be exported.
  • FormatType - Export File Format. Use Export.ExportFormat.CSV for the CSV file or Export.ExportFormat.Excel for the Excel file.
  • FileName - Export File Name.
    - For WebForms simply pass the filename. e.g. EmployeeInfo.xls
    - For WinForms pass the filename along with path. e.g. C:\\EmployeeInfo.csv
  • ColumnList - DataFields of the DataTable to be exported. Specify their ordinals in an integer array.
  • Headersrs - Custom Headers List for the specified columns in the export file. Specify the names in a string array.

You can call this method in the: ASPButton_Click event, LinkButton_Click event or Page_Load event or wherever you want. All you need to do is set the values to parameters and give a simple call to the required overload type of ExportDetails method.

The following is the code block that demonstrates "exporting specified columns" of a DataTable as an Excel file from WebForm.

[Code Behind]

private void btnExport2_Click(object sender, System.EventArgs e)
{
    // Export the details of specified columns

    try
    {
        // Get the datatable to export

        DataTable dtEmployee = ((DataSet) 
             Session["dsEmployee"]).Tables["Employee"].Copy();

        // Specify the column list to export

        int[] iColumns = {1,2,3,5,6};

        // Export the details of specified columns to Excel

        RKLib.ExportData.Export objExport = new 
            RKLib.ExportData.Export("Web");
        objExport.ExportDetails(dtEmployee, 
             iColumns, Export.ExportFormat.Excel, "EmployeesInfo2.xls");
    }
    catch(Exception Ex)
    {
        lblError.Text = Ex.Message;
    }
}

The following is the code block that demonstrates "exporting specified columns" of a DataTable as a CSV file from WindowsForm.

private void btnExportCSV_Click(object sender, System.EventArgs e)
{
    // Export the details of specified columns

    try
    {
        lblMessage.Text = "";
        
        // Get the datatable to export

        DataTable dtEmployee = dsEmployee.Tables["Employee"].Copy();

        // Specify the column list to export

        int[] iColumns = {1,2,3,5,6};

        // Export the details of specified columns to CSV

        RKLib.ExportData.Export objExport = new 
            RKLib.ExportData.Export("Win");
        objExport.ExportDetails(dtEmployee, 
            iColumns, Export.ExportFormat.CSV, 
            "C:\\EmployeesInfo.csv");
        lblMessage.Text = "Successfully exported to 
            C:\\EmployeesInfo.csv";
    }
    catch(Exception Ex)
    {
        lblMessage.Text = Ex.Message;
    }
}

Working with Demo Projects

To work with the WebForms Project in C#.NET

  1. Extract the ExportDemo_CSharpNet.zip file to a designated directory.
  2. Create a virtual directory in IIS with the name "ExportDemo_CSharpNet".
  3. Open up the demo solution ExportDemo_CSharpNet.sln in Visual Studio 2003.

To work with WebForms Project in VB.NET

  1. Extract the ExportDemo_VBNet.zip file to a designated directory.
  2. Create a virtual directory in IIS with the name "ExportDemo_VBNet".
  3. Open up the demo solution ExportDemo_VBNet.sln in Visual Studio 2003.

To work with WindowsForms Project in C#.NET

  1. Extract the ExportDemo_WindowsForms.zip file to a designated directory.
  2. Open up the demo solution ExportDataGrid.sln in Visual Studio 2003.

Points of Interest

  • This doesn't require any stuff like page register tags.
  • This can be used in WebForms as well as WinForms.
  • This uses the XML features of dataset and XSLT for the export functionality.
  • There is no looping through data elements.
  • Use the export object as many times as required and however you want since export functionality needs a single and simple call to Export object.
  • You can export as many datagrids as required on a single page.
  • You can specify the column list to export.
  • Even you can customize the headers of the export file.

History

  • Posted on 29th Sep, 2004.
  • Updated on 11th Oct, 2004. Updated files addresses export functionality from WinForms.
  • Updated on 10th Apr, 2007. Updated files' addresses regarding the problem of special characters in column names.

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

Rama Krishna Kolluri


Member
I am currently based in Hyderabad,India. I am a certified professional with an MCP in Developing WebForms and a Brainbench certified in .Net Framework. I am involved in Microsoft Windows/Web application development since 2001. Working on ASP.Net with C# for the past one year.

Rama Krishna,
kolluri.rk@gmail.com
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 25 of 247 (Total in Forum: 247) (Refresh)FirstPrevNext
GeneralHow to preserve leading zeros Pinmembermichael waller13:49 28 Oct '09  
GeneralFunny characters when exporting data to excel from aspx page PinmemberMember 270789018:44 13 Oct '09  
QuestionYour App has a Limitation....... PinmemberMadhu G12:46 5 Oct '09  
GeneralGood but Not a real excel file PinmemberMember 36709571:55 12 Aug '09  
GeneralRe: Good but Not a real excel file PinmemberFilipKrnjic14:49 19 Aug '09  
GeneralHow to save Exported excel Pinmembersravani060:46 12 Aug '09  
GeneralMy vote of 1 Pinmemberzephyrprime12:34 7 Aug '09  
GeneralExcel 2007 PinmemberRonsch22:47 21 Jul '09  
GeneralRe: Excel 2007 PinmemberAlmatrodi0:37 5 Aug '09  
GeneralRK LIB-HEADING ALONG WITH COLUMN Pinmemberraja mohamed3:25 21 Jul '09  
GeneralFormat datetime and string !? PinmemberNguyenDzung0:27 8 Jul '09  
QuestionNullReferenceException Pinmemberkjanamanchi8:44 6 Jul '09  
GeneralVery good article PinmemberDiya1420:28 28 Jun '09  
GeneralSharepoit 2007! PinmemberErka13:02 26 Jun '09  
General@ in column name Pinmembermikethelad4:54 17 Jun '09  
GeneralUnable to evaluate expression because the code is optimized or a native frame is on top of the call stack. PinmemberJeevaBharathi0:50 6 May '09  
NewsUnicode Pinmemberkinaï5:33 1 Apr '09  
GeneralRe: Unicode Pinmemberrastlin20210:49 22 Apr '09  
GeneralXSLT compile error at (5,198). See InnerException for details. Pinmemberzhuoming6:34 18 Mar '09  
GeneralMy vote of 2 PinmemberDaniel Ballinger16:14 8 Mar '09  
QuestionStrange error. with column name. please help... PinmemberMember 237397922:46 15 Feb '09  
AnswerRe: Strange error. with column name. please help... PinmemberMember 237397922:50 15 Feb '09  
GeneralMy vote of 2 Pinmemberwmjordan19:50 19 Dec '08  
QuestionUnicode support? Pinmemberwinchnet200515:20 10 Dec '08  
GeneralGood article Pinmembermonknet2:44 10 Dec '08  

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

PermaLink | Privacy | Terms of Use
Last Updated: 12 Apr 2007
Editor: Sean Ewington
Copyright 2004 by Rama Krishna Kolluri
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project