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

One click ASP.NET export button control for Excel/CSV file

By , 8 Dec 2004
 

Sample image

Introduction

Microsoft has done a wonderful job of creating an extensible framework, especially for ASP.NET, by creating various server controls. This article is about extending ASP.NET Button control and adding your own functionality for ONE CLICK exporting from ASP.NET page.

Background

There are various ways one can export data using ASP.NET. Usually, it is done by coding a separate page and adding various HTTP headers and responses. (Refer: Microsoft).

Like me, most of us believe in reuse. The export functionality can be achieved by reusing the same page for various projects either by passing DataSet from the parent page, or reconnecting to the data source on the landing page and manipulating Response object.

One Click Export

You may wonder why I call it ONE CLICK EXPORT, 'because this control doesn't require intermediate page for exporting data'. Just drag the ExportButton control on an ASPX page or a user control, and set its properties at design time or runtime to hook DataView. Yup, that’s it, no more hassles of dealing to investigate HTTP headers, MIME types or encodings.

'ASPX page [Design time]
…
…
<pnwc:ExportButton id="btnExcel" runat="server" 
  Separator="TAB" Text="Export to Excel" 
  FileNameToExport="Books.xls" BackColor="#E0E0E0"></pnwc:ExportButton>
….
….

'Code Behind [Run time]
    Private Sub Page_Load(ByVal sender As System.Object,_
             ByVal e As System.EventArgs) Handles MyBase.Load
        Dim ds as dataset=filldataset()
        dgBooks.DataSource = ds.Tables("Books")
        dgBooks.DataBind()
            
        'Set Export button properties 
        btnExcel.Dataview = ds.Tables("Books").DefaultView
        btnExcel.FileNameToExport = "Books.xls"
        btnExcel.ExportType = _
          PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel
        btnExcel.Separator = _
          PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB

    End Sub

[Note: The ExportButton properties can either be set at design time and/or run time].

Properties Explained

  • ExportType [CSV or EXCEL]
  • Separator [Comma or TAB]
  • Delimiter [Any character]

ExportType property is used to either select CSV or EXCEL format, btnExcel.ExportType = PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel. Separator property can be used to either select TAB or Comma separator, btnExcel.Separator = PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB. Delimiter property is used to specify any delimiter like single quote, double quote, pipe character etc. Default is Nothing (empty string).

Demo code

The source code is provided with the sample project to test out the solution.

  1. Install is straightforward. Extract demo code zip files to a designated directory.
  2. Two directories will be created. (namely, \\PNWebControls and \\TestMyControls). Make sure they both fall under same parent directory.
  3. Create a virtual directory by either right clicking on the directory \\TestMyControls and opening properties for web share, or use IIS MMC. (Note: This is a demo project.)
  4. Open up a demo solution (TestPNControls.sln) in Visual Studio 2003. (This control also works well with VS 2002. You know the drill, just change the version numbers inside the project/solution file and open it in Visual Studio 2002).

How to use the Control in your project

You may either include the PNWebControls project and reference it in your project, or reference the assembly (PNayak.Web.UI.WebControls.ExportButton.dll). You can also add this control in Visual Studio Toolbox for design time.

[Note: This assembly also contains ExportLinkButton as some may prefer link button over regular button.]

Check out my .NET spot for more to discover.

History

  • 8 July 2004 - updated downloads.
  • 9 Dec 2004 - updated downloads and article.

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

Prashant Nayak (.Net Lover)
Web Developer
United States United States
Cranking code more than 12 years. Technical/Project lead/MCSD. Offered services to various industuries like S/W, Telecom, Publishing, Insurance etc.
 
When not on computer, I play/swim/read with my kids and help my better half (of course my lovely wife) to clean house. Solving challenging S/W problems is my passion. Hate non-productive meetings. Do lots of GOOGLE and Eat/Drink/Sleep around MSDN.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 Pinmemberm3jim11-Jan-13 1:48 
Great control - worked the first time !!!
Answerunicode problem Pinmemberkamran_kamaei29-Nov-11 14:53 
I solved the unicode problem by doing adding this line to the customExport()
 
Dim Encoding As New System.Text.UnicodeEncoding
            response.ContentEncoding = System.Text.Encoding.Unicode
            response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
 
plz check it and let me know if its works for u too
Questionwhen I click on export button broser shows me msg "Internet Explorer cannot display the webpage " ..plz help urgent ! Pinmemberanjaliaroraverma26-Sep-11 18:41 
hi Prashant,
 
Excellent code can you please guide me further ... thanks a lot....
 
when I click on export button broser shows me msg "Internet Explorer cannot display the webpage " ..plz help urgent !
AnswerRe: when I click on export button broser shows me msg "Internet Explorer cannot display the webpage " ..plz help urgent ! Pinmemberanjaliaroraverma26-Sep-11 19:00 
GeneralRe: when I click on export button broser shows me msg "Internet Explorer cannot display the webpage " ..plz help urgent ! PinmemberMember 97423229-Jan-13 2:48 
GeneralRe: when I click on export button broser shows me msg "Internet Explorer cannot display the webpage " ..plz help urgent ! Pinmemberthedarkone210-May-13 0:26 
GeneralHow to use the code in c# Pinmembersridharan282-Jun-11 19:29 
Hai,
 

I want the same code in c# .net.plz will you help me for this
GeneralMy vote of 1 PinmemberEng Basel27-Apr-11 2:32 
khra
GeneralMy vote of 1 Pinmembergandhiabc4u13-Apr-11 23:54 
hi
GeneralNo data found when using export button Pinmembercfchapman4-Aug-10 7:56 
Hi everyone. I have an issue using the export to csv button. I can't seem to pull any data. The code executes without error but my download csv file is always the empty dataset not a populated one. I can't seem to determine where to associate the dataset to the control correctly at design time. Here's a code snippet:
 
<asp:RoleGroup Roles="My Store";
<ContentTemplate>
<strong> Online Store
<br />Order Report</strong>&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<hr />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataSourceID="AccessDataSource1" PageSize="50">
<Columns>
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="OrderNumber" HeaderText="Order#"
SortExpression="OrderNumber" />
<asp:BoundField DataField="ItemNumber" HeaderText="Web Order #"
SortExpression="ItemNumber" />
<asp:BoundField DataField="DetailDate" HeaderText="Date"
SortExpression="DetailDate" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="ProductTotal" HeaderText="Product Total"
SortExpression="ProductTotal" />
<asp:BoundField DataField="Discount" HeaderText="Credit Due"
SortExpression="Discount" />
<asp:BoundField DataField="SKU" HeaderText="SKU" SortExpression="SKU" />
<asp:BoundField DataField="Product" HeaderText="Product Name"
SortExpression="Product" />
<asp:BoundField DataField="QuantityOrdered" HeaderText="Ordered"
SortExpression="QuantityOrdered" />
<asp:BoundField DataField="QuantityShipped" HeaderText="Shipped"
SortExpression="QuantityShipped" />
<asp:BoundField DataField="Backordered" HeaderText="Back Ordered"
SortExpression="Backordered" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
 
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="C:\StoneEdge\LifeTeen.mdb"
SelectCommand="SELECT Orders.Name, Orders.ProductTotal, Orders.Discount, [Order Details].OrderNumber, [Order Details].DetailDate, [Order Details].Product, [Order Details].SKU, [Order Details].ItemNumber, [Order Details].Status, [Order Details].QuantityOrdered, [Order Details].QuantityShipped, [Order Details].Backordered FROM (Orders INNER JOIN [Order Details] ON Orders.OrderNumber = [Order Details].OrderNumber)
">
</asp:AccessDataSource>
</ContentTemplate>
</asp:RoleGroup>
 
<pnwc:ExportButton ID="ExportButton1" runat="server" Text="Export Report" />
 

I always get an empty csv file. Please help. Thanks Chris
GeneralError Display unicode letter In Excel PinmemberDongMT2-Aug-10 23:44 
I found an error in display text when I open exported file in MS Excel
 
The Unicode character such as "Ô", "ư" (Vietnamese language)... cannot display correctly.
 
But When I open this file in Open Office 3.2. it's display correctly.
 
I dont know why. Could I solve this problem?
 
Thanks for demo. It's great!
 
DongMT
QuestionFormatting a Integer column to String PinmemberSibiSurya10-May-10 3:29 
First of all Thank you very much for the Control.
Good Work!!!.
 
Just one small query
 
When I export I have in datatable one column values as "0405", "0302" etc. But When I export to Excel the data in the column becomes "405", "302".
 
HOw to format a specified column as Text using your Export button.
 
Please do Reply. Its urgent.
QuestionTotal Noob begging for someones help PinmemberPhil Lavender12-Dec-09 1:37 
Im brand new to asp.net but im getting there quite quickly. I really need to use this contol for a project at work but i don't know where to start with it, this is what i've done so far:
 
Using Visual Web Developer Express I started a new project and opened default.aspx and default.aspx.vb, added an access datasource, added a gridvew and then added the export button which i had added to my toolbox.
 
Now i know i need to set the dataview for the button but i dont know how/where to do this.
 
lets say my datasource is called Data1 and the table im using is called Table1 and my datagrid is called Grid1
 
Someone please help me, i will be so very grateful.
 
P
Questionresponese.end error message PinmemberMember 404560329-Aug-09 2:42 
every thing is working fine. but in stop execution
"response.End()"
an error occurs 'property evaluation failed.'
But file is generated successfully. how to fix it...
AnswerRe: responese.end error message PinmemberLoki7021-Oct-09 5:12 
AnswerRe: responese.end error message PinmemberV.Manjunath11-Jan-11 8:57 
GeneralExport to excel not CSV Pinmembertorchwood90915-Jun-09 6:00 
<myControl:ExportButton id="bExportToExcel" runat="server"
Separator="TAB" Text="Export to Excel"
FileNameToExport="Filename.xls" BackColor="#E0E0E0" />
 

This code seems inaccurate...
 
Separator="TAB" reminds me of exporting to CSV...is it also accurate for Excel...
Can this library export to Excel? or only to CSV...I understand that it can, but I could be wrong...
GeneralRe: Export to excel not CSV Pinmembergg423721-Aug-09 5:30 
GeneralRe: Export to excel not CSV PinmemberCikaPero15-Sep-10 22:18 
GeneralExport to Excel using this library IN A USER CONTROL Pinmembertorchwood90915-Jun-09 5:54 
The difficulty I'm having with the library or any other code I write is that I need my code to act as a user control so that from the EXCEL button SEVERAL grids in .NET will be exported to Excel
 
I have code that works by exporting HTML to excel but I really do need Excel to open an excel document which is whY I chose this library...
 
Here's my code so far, but I get an error in this line: da.Fill(myDS, "myRecordsDataTable")
Of course that makes perfect sense becasue this line is not the type of line that would work with several datagrids, or datatables, on the contrary, it seems to require a specific table...
 
Can you help me fix this? Does the rest of my code look okay, am I on the right track?
 

 
Imports System.Data
 
Partial Class common_code_ExportToExcel
Inherits System.Web.UI.UserControl
 

Dim mGv As Control
Dim mFilename As String = "Filename.xls"
Dim mFilldataset As Control
Dim mOpenOnly As Boolean = False
 
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
Dim ds As DataSet = GetRecords()
 
'Set Export button properties
btnExcel.FileNameToExport = "Filename.xls"
btnExcel.FileNameToExport = "ExcelExport" + System.DateTime.Now.Ticks.ToString() + ".xls"
btnExcel.ExportType = PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel
'btnExcel.Separator = PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB
 
End Sub
 

Private Function GetRecords() As DataSet
Dim myDS As New DataSet()
 
'Dim d As New db
Dim d As New SqlClient.SqlConnection("Data Source=db")
'Using myConn As New db
Using da As New SqlClient.SqlDataAdapter("SELECT * FROM MyTable", d)
da.Fill(myDS, "myRecordsDataTable")
End Using
'End Using
 
'da.DataSource = myDS.Tables(0)
'da.DataBind()
 
Return myDS
End Function
End Class
Generalfilldataset Pinmembertorchwood90911-Jun-09 9:51 
What do I place instead of filldataset?
That's what I get stuck...
AnswerRe: filldataset Pinmembermusacj11-Jun-09 22:35 
GeneralRe: filldataset Pinmembertorchwood90915-Jun-09 4:36 
AnswerRe: filldataset Pinmembermusacj15-Jun-09 5:00 
GeneralRe: filldataset Pinmembertorchwood90916-Jun-09 7:03 
AnswerRe: filldataset Pinmembermusacj17-Jun-09 0:23 
QuestionCan someone help me to do this from a user control from a datasource? Pinmembertorchwood90911-Jun-09 9:42 
'this is my code, but I do not know how to implement this library with it... I added the library, but now I don't know how to use it...
 
'Dim mGv As GridView
Dim mGv As Control
Dim mFilename As String = "Filename.xls"
Dim mOpenOnly As Boolean = False
 
Public Property OpenOnly() As Boolean
Get
Return mOpenOnly
End Get
Set(ByVal value As Boolean)
mOpenOnly = value
End Set
End Property
 
Public Property Filename() As String
Get
Return mFilename
End Get
Set(ByVal value As String)
mFilename = value
End Set
End Property
 

Public Property DataSource() As Control
Get
Return mGv
End Get
Set(ByVal value As Control)
mGv = value
 
Dim c As Control = mGv
 
Dim up As UpdatePanel = controlType(c, New UpdatePanel)
 
If Not up Is Nothing Then
If up.Triggers.Count = 0 Then
Throw New Exception("Export To Excel Object appears to be in a Updatepanel. Please set <asp:PostBackTrigger ControlID='ExportGridViewToExcel1' /> in the updatepanel")
Else
 
For lcv As Integer = 0 To up.Triggers.Count - 1
If Not up.Triggers.Item(lcv).ToString.Contains(Me.ID) Then
Throw New Exception("Export To Excel Object appears to be in a Updatepanel. Please set <asp:PostBackTrigger ControlID='ExportGridViewToExcel1' /> in the updatepanel")
End If
Next
End If
 
End If
End Set
End Property
 
Private Function controlType(ByVal c As Control, ByVal searchFor As Control) As Control
Dim foundcontrol As Control = Nothing
If c.GetType.Equals(searchFor.GetType) Then
foundcontrol = c
Else
If Not TypeOf c.Parent Is Page Then
foundcontrol = controlType(c.Parent, searchFor)
End If
End If
 
Return foundcontrol
End Function
AnswerRe: Can someone help me to do this from a user control from a datasource? Pinmemberpsit5716-Jul-09 8:47 
Generalfile transfer to mobile phone Pinmembersakshi singla15-Mar-09 2:48 
hi
can u plz tell me hw can i transfer a text file from my web application(on button's click) in asp.net to my GPRS enabled mobile phn...
plz help me out as soon as possible
GeneralDataview Export to excel - Messed up excel sheet Pinmembererkrsr30-Nov-08 18:35 
Hi,
I am trying to export the gridview data to excel 2003 through ASP .NET. I could see the data in excel 2003, the only problem is the format of generated excel is coming as the Gridview and not in the normal excel cells. i.e. i am not able to see the cell data.
e.g. Cell B1 has data 120 but when i select this cell, this value does not appear in excel formula bar. So i could not use any formula to show the same data in another sheet etc.
 
The code is:
 
protected void ExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = false;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
Page.EnableViewState = false;
// If you want the option to open the Excel file without saving then
// comment out the line below
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DFTGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
 
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
QuestionRe: Dataview Export to excel - Messed up excel sheet Pinmembertorchwood90911-Jun-09 9:40 
GeneralRe: Dataview Export to excel - Messed up excel sheet Pinmembergg42375-Nov-09 0:41 
GeneralUsing with SSL PinmemberAndrew Woomer13-Nov-08 9:56 
Are there any know issues using this control with SSL?
 
Andrew Woomer

GeneralIf using this with Ajax update panel - you better do this... Pinmemberilovthecov27-Oct-08 13:22 
Make sure the button/link are not inside of the update panel... Ajax does async call for the update panels and the response.write to the response object will result in an error. Otherwise, I'm very happy to have such a nice control to use and I thank the author...
GeneralRe: If using this with Ajax update panel - you better do this... PinmemberMember 398938613-Mar-09 0:06 
QuestionHow do you format the Excel output? Pinmember5150.Net14-Oct-08 7:31 
Is this control flexible enough to let us format the Excel output before the end user sees it? I'm seeing all the columns squished together and some columns need to be right or left justified at times.
 
Thanks for firing me Darrell Eaker of Ringgold Telephone Company. I TRIPLED my salary and don't have to deal with douchebags like you. Smile | :)

QuestionCan I use this control in Datagrid ? Pinmemberthakar10-Sep-08 0:45 
Can i use this control in datagrid temlate column. I have list of file and user can select button n down load it.
I did but not getting result.
GeneralFormat PinmemberMember 172018313-Mar-08 7:49 
When I open excel file, I get a message "File is not in recognizabe format." Yet when I click "OK" it opens fine.
 
Please help
 
andrey
GeneralRe: Format PinmemberAlex Tang21-Apr-08 19:18 
GeneralRe: Format PinmemberSandeep.Ban27-May-08 21:45 
GeneralRe: Format Pinmember5150.Net14-Oct-08 7:19 
GeneralRe: Format Pinmemberjesiahwedgewood27-Apr-09 12:56 
GeneralRe: Format Pinmembergtxboyracer8-Feb-10 10:34 
GeneralProblem PinmemberMember 172018312-Mar-08 9:52 
I created this button but it doesn't executes properly, and I can't pass dataset.
 
Protected Sub ExportButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExportButton1.Click
Dim _dataPool As New DataPool
Dim _ds As New DataSet
Dim _myparams(1) As DataPool.StoredProcedureParams
 
'Gets data from a table
 
_myparams(0).sname = "@begin_date"
_myparams(0).edirection = ParameterDirection.Input
_myparams(0).vvalue = txtFrom.Text
_myparams(1).sname = "@end_date"
_myparams(1).edirection = ParameterDirection.Input
_myparams(1).vvalue = txtTo.Text
_dataPool.ConnectionServer = "Connection" 'Specifies Connection Server
_ds = _dataPool.GetDataSet("sp_New_Items", _myparams)
ExportButton1.Dataview = _ds.Tables(0).DefaultView
ExportButton1.FileNameToExport = "NewItemsCataloged.xls"
ExportButton1.ExportType = PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel
ExportButton1.Separator = PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB
 
End Sub
 
It doesn't execute this code at all.
 
Please help
GeneralRe: Problem [modified] Pinmemberpsit5715-Jul-09 10:14 
Generalexcel report in asp.net Pinmembersehgalama30-Jan-08 19:40 
hi all
 
can anybody help me how to create excel report using the data from oracle in asp.net
 
plz help me its very urgent for me
thnkx in advance
aman
GeneralRe: excel report in asp.net Pinmembermauxanhlam12-Jun-08 21:51 
NewsAlternative Solution [modified] Pinmemberkelvin199718-Nov-07 18:30 
If you think creating another page called "ExportFile.aspx" is no trouble at all, then you can do the following:
(NOTE! this solution still only just do ALL the job on your CURRENT PAGE, will NOT negative your browser to "ExportFile.aspx")
 
----------------------------------------
"ExportFile.aspx" make this...
<%@ Page Language="CS" AutoEventWireup="false" CodeFile="ExportFile.aspx.vb" Inherits="ExportFile" %>
----------------------------------------
"ExportFile.aspx.cs" make this...
protected void Page_Load(object sender, EventArgs e)
{
string FileResponse = Session.Item("FileExport");
Response.AddHeader("Content-disposition", "attachment; filename=report.csv");
Response.ContentType = "application/octet-stream";
Response.Write(FileResponse);
Response.End();
}

----------------------------------------
"YourOwnPage.aspx" add this...
asp:Button runat="server" ID="ExportButton" Text="Export Report">
----------------------------------------
 
"YourOwnPage.aspx.cs" add this...
private void ExportButton_Click(object sender, System.EventArgs e)
{
string buffer = GenerateFile();
If (Session.Item("ExportFile") == Nothing)
{ Session.Add("ExportFile",""); }
Session.Item("ExportFile") = buffer;
Response.Redirect("ExportFile.aspx");
}

----------------------------------------
private string GenerateFile()
{
//do something here yourself
}

---------------------------------------
 

done! WTF | :WTF: Rose | [Rose]
 
Reference Source:
AJAX, Use IFRAME to open/download file on same page.
http://encosia.com/2007/02/23/ajax-file-downloads-and-iframes/
 
kelvin1997
AnswerRe: Alternative Solution Pinmemberkelvin199718-Nov-07 18:35 
AnswerAbout Excel and my GenerateFile() function Pinmemberkelvin199718-Nov-07 19:17 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 9 Dec 2004
Article Copyright 2004 by Prashant Nayak (.Net Lover)
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid