All in One Export Data in ASP.NET, Gridview to DOC – Gridview to Excel – Gridview to PDF

Prabhakar
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 79831 red flag
Rating: 5 out of 5  
 3 vote(s)

In this article I have shown power of ASP.NET to export data to excel, pdf and doc. Other softwares that uses these extension gives flexibility of sorting, searching and security. In a article you will get some good tricks to Export data in excel, documents & PDf Files.


 Download source code for All in One Export Data in ASP.NET, Gridview to DOC – Gridview to Excel – Gridview to PDF


In .aspx Page

On .aspx page  firstly add controls. TextBox’s & Button’s and Gridview. Firstly I am write a query in text Box then Click GO button Fill a Gridview Then I am Using Three Buttons Export to Word, Export to Excel, Export to PDF

Export to Word

In a export to word Write this code on btnexporttoword Click event.

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 Dilog Box Open



Export to Excel

In a export to excel Write this code on btnexporttoExcel  Click event.

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 Dilog Box Open

 

 

Export to Pdf

You want to Export  Gridivew to  PDF so frstly add these .dll  itextsharp.dll

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

Then add some namespaces

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

In a export to pdf Write this code on btnexporttoPdf  Click event.

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 Dilog Box Open

 

Page copy protected against web site content infringement by Copyscape

About the Author

Prabhakar
Full Name: prabhakar parihar
Member Level:
Member Status: Member,MVP
Member Since: 1/12/2011 5:05:40 AM
Country: India
Best Regard's Prabhakar
http://www.dotnetfunda.com
Currently working as a Software Engineer (Developer) [ ASP.NET , C# ]

Login to vote for this post.

Comments or Responses

Posted by: Karthikanbarasan on: 2/4/2011 | Points: 25
Hi Prabhakar,

Nice article and it will be good for many users since export from the grid view is needed in daily coding process...


Posted by: Prabhakar on: 2/5/2011 | Points: 25
Hi Karthikanbarasan


thanks for responding on my article ..
Posted by: Sutotpal on: 2/5/2011 | Points: 25
It's also nice article from u, dude..
Keep it up..
Posted by: Prabhakar on: 2/5/2011 | Points: 25
Hi Sutotpal,


thanks for responding ... i am try to my best in future ...
Posted by: Naimishforu on: 2/7/2011 | Points: 25
Hi, Thanks for the same.

It would be nice if you can provide the downloadable source code also.

Thanks :)
Posted by: Prabhakar on: 2/7/2011 | Points: 25
HI , Naimishforu

thanks for responding . your suggestion is good , i am attach source code with this article now . .
Posted by: Mauryavijai on: 2/7/2011 | Points: 25
Prabhakar,

Nice Article
Posted by: Naimishforu on: 2/7/2011 | Points: 25
Hi,

Thanks, did you attached it?? Can you please tell me how to download it? I can't find it :(

Thanks.
Posted by: Prabhakar on: 2/8/2011 | Points: 25
Hi Naimishforu


sorry forlate attaching source code .. Click on Download link you Download the Source Code ..
Posted by: Naimishforu on: 2/8/2011 | Points: 25
Hey Thanks....got the code :) will try it out.....thank you very much.
Posted by: Naimishforu on: 2/8/2011 | Points: 25
Hi, Thanks.

I have looked into your download you have provided.

No doubt it's good but I have a suggestion here.

Can you please provide the completed build solution for downloading so that if anyone want's to directly try out the demo, he/she can.

Here I have to create a new solution and need to add your files into my solution and than I'll have to try.

Please correct me if I am wrong.

Thanks, by the way pretty nice things you have done :)
Posted by: Prabhakar on: 2/8/2011 | Points: 25
hi Naimishforu,

i think it's ok for all users .. just add this page & .dll for Your Project ... Whole Project Attach this time not possible for me ..
Posted by: Max_India7 on: 10/4/2012 | Points: 25
Sir,
Can i use it ....with Master page and content page scenerio.....


Posted by: Bhanubysani on: 11/28/2012 | Points: 25
Hi prabhakar,

I am exporting a panel to pdf using above code in webpart using below code

DataSet dsAccountData = (DataSet)Session["DataSource"];
if (dsAccountData != null && dsAccountData.Tables[0].Rows.Count > 0)
{

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();
this.pnl1.Parent.Controls.Add(frm);
// frm.Attributes["runat"] = "server";
frm.Controls.Add(this.pnl1);
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 exporting to PDF some unwanted headers are adding which are not required above and below of the content.I followed different URLs.some of the codes are working good in asp.net webpages.
Because in that pages i am able to write the below method which i can't write in webpart or usercontrol.

Please find this attachment,please help me.This type of headers are adding above and below the code. I think this is top and bottom of the page.i am not sure about that.

//var theForm = document.forms['aspnetForm']; if (!theForm) { theForm = document.aspnetForm; } function
__doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit(); } } ////var MSOWebPartPageFormName = 'aspnetForm'; var g_presenceEnabled = true;
var g_wsaEnabled = false; var g_wsaLCID = 1033; var g_wsaSiteTemplateId = 'STS#0'; var
g_wsaListTemplateId = 850; var _fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\u002f",
webLanguage: 1033, currentLanguage: 1033, webUIVersion:4,pageListId:"{12e3d35a-1bde-402c-910af18ab0398d16}",
pageItemId:1,userId:2, alertsEnabled:true, siteServerRelativeUrl: "\u002f",
allowSilverlightPrompt:'True'};////var dlc_fvsi = {"DefaultViews":[],"ViewUrls":[],"WebUrl":"\/"};////function
_spNavigateHierarchy(nodeDiv, dataSourceId, dataPath, url, listInContext, type) {
CoreInvoke('ProcessDefaultNavigateHierarchy', nodeDiv, dataSourceId, dataPath, url, listInContext, type,
document.forms.aspnetForm, "", "\u002fPages\u002fReportTool.aspx"); } ////function WebForm_OnSubmit()
{ UpdateFormDigest('\u002f', 1440000); return true; } //

Login to post response

Comment using Facebook(Author doesn't get notification)