Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET

All in One Export Data in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.82/5 (14 votes)
22 May 2011CPOL1 min read 124.8K   52   13
All in One Export Data in ASP.NET, Gridview to DOC – Gridview to Excel – Gridview to PDF

Introduction

In this post, I will show the power to export data to other document software. In other software, you have a lot of work that can be done in an easy manner. For sorting, searching and security purposes, you do not want to give data Excel & Doc format, so you use Export GridView to PDF.

In this post, you can read some good tricks for exporting data in documents & PDF files.

In .aspx Page

In the .aspx page, firstly add controls, TextBox and Button and Gridview. First, I write a query in text box, then click GO button, fill a Gridview. Then I use three buttons export to Word, Export to Excel, Export to PDF.

Export to Word

In an export to Word, write this code on btnexport towards the Click event.

C#
Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(htmlWrite);
//GridView1.RenderControl(htw);
Response.Write(stringWrite.ToString());
Response.End();

After click, one Save As Dialog Box opens:

 

Export to Excel

In an export to Excel, write this code on btnexporttoExcel Click event.

C#
string attachment = "attachment; filename=Export.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(htw);

//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

After Click, one Save As Dialog Box opens.

Export to PDF

You want to export Gridview to PDF, so first add the itextsharp.dll.

Link: http://sourceforge.net/projects/itextsharp/

Then add some namespaces:

C#
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

In an export to PDF, write this code on btnexporttoPdf Click event.

C#
Response.ContentType = "application/pdf";

Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

After Click, one Save As Dialog Box opens:

License

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


Written By
Software Developer Mencentric Infotech Pvt.Ltd.
India India
I am Software Developer . .

Comments and Discussions

 
QuestionExport Panel Content to pdf not working Pin
Manish Goswami28-Nov-14 18:15
Manish Goswami28-Nov-14 18:15 
I want to export panel content in pdf but i am getting error, in panel i have table and Gridview.

ASPX Page :

<asp:panel id="pnl_export" runat="server">

<asp:label id="rptname" runat="server" text="">
<asp:label id="lbid" runat="server">
<asp:label id="lbexp" runat="server" text="Report Exported On : ">
<asp:label id="lbdate" runat="server">
<asp:label id="lfrm" runat="server" text="From : ">
<asp:label id="fdate" runat="server">
<asp:label id="lto" runat="server" text="To : ">
<asp:label id="tdate" runat="server">



<asp:gridview id="GridView1" runat="server" width="63%" align="Center" pagesize="20"
="" allowpaging="true" onrowdatabound="GridView1_RowDataBound" onpageindexchanging="GridView1_PageIndexChanging">
<alternatingrowstyle backcolor="White" forecolor="#284775">
<pagersettings mode="NextPreviousFirstLast" firstpagetext="First" lastpagetext="Last"
="" nextpagetext="Next" previouspagetext="Prev" position="TopAndBottom">



Code Behind for pdf Export :

protected void pdfExport_Click(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
// GridView1.AllowPaging = false;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=AgentReport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
pnl_export.RenderControl(hw);
String htmlString = sw.ToString().Substring(0, sw.ToString().Length - 1);
StringReader sr = new StringReader(htmlString);
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
pdfDoc.Open();
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

htmlparser.Parse(sr);
pdfDoc.Close();

Response.Write(pdfDoc);
Response.End();

}

}


}
It's not working giving me error,

Error : Unable to cast object of type 'iTextSharp.text.html.simpleparser.TableWrapper' to type 'iTextSharp.text.ITextElementArray'.
HTML Content :





Agent Report For AgentID :
RSBOM0400986
Report Exported On :
10:01:34 AM
From :
25/11/2014
To :
28/11/2014

Sr.NoSales PersonRemarkDate Visited
1Manish Goswami-700145fhvhvhffffffftt26-Nov-14 5:53:49 PM
2Manish Goswami-700145remark km from my name of the way to26-Nov-14 5:59:23 PM



Please help me out to solve this error.Thanks in advance.
Questionwhat is gv in the code ??<pre lang="c++"></pre> Pin
Member 105441282-May-14 11:30
Member 105441282-May-14 11:30 
Question[My vote of 1] it is showing html tags in word file. Pin
abdussalam14328-Nov-13 1:40
professionalabdussalam14328-Nov-13 1:40 
GeneralMy vote of 5 Pin
rmksiva18-Apr-13 3:41
professionalrmksiva18-Apr-13 3:41 
GeneralExporting GridView data to PDF with sugession Pin
varaprasadreddy.bh30-Aug-12 5:13
varaprasadreddy.bh30-Aug-12 5:13 
QuestionBetter HTML to PDF export Pin
Member 902839525-May-12 2:30
Member 902839525-May-12 2:30 
QuestionExport with formatting to PDF Pin
Vrushali Sawant23-Apr-12 1:33
Vrushali Sawant23-Apr-12 1:33 
QuestionExcel export in ASP.NET Pin
CikaPero19-Jul-11 22:25
CikaPero19-Jul-11 22:25 
GeneralError in line frm.RenderControl(htw); Pin
marianomolina1514-Jun-11 11:29
marianomolina1514-Jun-11 11:29 
RantMy, but aren't we supportive. Pin
Brian Stevens24-May-11 17:55
Brian Stevens24-May-11 17:55 
GeneralMy vote of 5 Pin
Brian Stevens24-May-11 17:49
Brian Stevens24-May-11 17:49 
Generalwarnings etc Pin
dave.dolan23-May-11 4:47
dave.dolan23-May-11 4:47 
GeneralNot an article Pin
R. Giskard Reventlov23-May-11 0:04
R. Giskard Reventlov23-May-11 0:04 

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.