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.

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
