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

All in One Export Data in ASP.NET

By , 22 May 2011
 

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.

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.

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:

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.

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)

About the Author

prabhakarparihar
Software Developer Mencentric Infotech Pvt.Ltd.
India India
Member
I am Software Developer . .

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 5memberrmksiva18 Apr '13 - 3:41 
Very Nice Article
GeneralExporting GridView data to PDF with sugessionmembervaraprasadreddy.bh30 Aug '12 - 5:13 
Hi Hear is the solution with details and solution for the problems when exporting Click Here
QuestionBetter HTML to PDF exportmemberMember 902839525 May '12 - 2:30 
First I used this solution to export my html to pdf but I found the output PDF is not keeping the exact styles. itextsharp is great but for tidy results you need a professional html to pdf converter tool like the one from hiqpdf
QuestionExport with formatting to PDFmemberVrushali Sawant23 Apr '12 - 1:33 
Hi,
 
I wanted to export html to PDF along with css attached to that element.
e.g. I am creating chart using JQuery and CSS that should be export to PDF as it is.
I am doing all this in .net 4.0.
 
Please suggest how to do that.
QuestionExcel export in ASP.NETmemberCikaPero19 Jul '11 - 22:25 
There is also a much cleaner way for Excel exporting in your Excel ASP.NET applications, with this Excel C# / VB.NET component.
 
Here is an Excel C# code sample:
DataTable people = (DataTable)Session["people"];
 
// Create excel file.
ExcelFile ef = new ExcelFile();
ExcelWorksheet ws = ef.Worksheets.Add("DataSheet");
ws.InsertDataTable(people, "A1", true);
 
Response.Clear();
 
// Stream file to browser, in required type.
switch (this.RadioButtonList1.SelectedValue)
{
    case "XLS":
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
             "Report.xls");
        ef.SaveXls(Response.OutputStream);
        break;
 
    case "XLSX":
        Response.ContentType = "application/vnd.openxmlformats";
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
             "Report.xlsx");
        // With XLSX it is a bit more complicated as MS Packaging API
        // can't write directly to Response.OutputStream.
        // Therefore we use temporary MemoryStream.
        MemoryStream ms = new MemoryStream();
        ef.SaveXlsx(ms)
        ms.WriteTo(Response.OutputStream);
        break;
}
Response.End();
 
And here is a live web demo: Excel ASP.NET export demo.
GeneralError in line frm.RenderControl(htw);membermarianomolina1514 Jun '11 - 11:29 
The code does not control user System.InvalidOperationException
Message = You can only call RegisterForEventValidation during Render ();
Source = System.Web
 
The grid is filled with a true picture if all display shows a cross
RantMy, but aren't we supportive.memberBrian Stevens24 May '11 - 17:55 
Might not meet your definition of an 'article', but the code is plenty clear to most anyone.
 
For one, I get tired of lengthy articles which just explain what should be obvious from the code comments (if they were indeed done well).
 
How about Contributing rather than Criticizing.
Charlie

GeneralMy vote of 5memberBrian Stevens24 May '11 - 17:49 
As a seasoned programmer, this article is just what I need to start down a track on something I've never done.
 
Thank you!
Generalwarnings etcmemberdave.dolan23 May '11 - 4:47 
If you export to excel via html, you get a warning trying to open it in Excel that the format of the document doesn't appear to match the expected content. It still opens ok if you try it, but I'd imagine this is a very dirty dirty thing to expect your users to deal with. I mean, we want them to get content without ignoring security warnings.
 
This also doesn't appear to be an article... it's more like a few snippets and notes.
GeneralNot an articlememberdigital man23 May '11 - 0:04 
Perhaps a blog post or tip/trick. Take away the images and code blocks and there is nothing left.
"If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair.
nils illegitimus carborundum
 
me, me, me

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 22 May 2011
Article Copyright 2011 by prabhakarparihar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid