Loading ...

Export ASP.NET page to Word, Excel or PDF

0 (0votes)

Many times we would like to export our page as an Excel sheet, Word doc or PDF file. This can be simply achieved by changing the ContentType of the Response object and overriding the RenderControl method of the control to be exported:

Page Load()
 //bind data to data bound controls and do other stuff

Response.Clear(); //this clears the Response of any headers or previous output
Response.Buffer = true; //make sure that the entire output is rendered simultaneously

///Set content type to MS Excel sheet
///Use "application/msword" for MS Word doc files
///"application/pdf" for PDF files

Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter(); //System.IO namespace should be used

HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

///Render the entire Page control in the HtmlTextWriter object
///We can render individual controls also, like a DataGrid to be
///exported in custom format (excel, word etc)
} //end page load

For exporting ASP.NET pages as PDF files, you need to know the Adobe PDF specs for generating the PDf correctly. There is already a wonderful component which does the same and its free! See this article along with sample source code on how to export a page to PDF:


Hope this would be helpful...!

Comments (2)

Stephen Borg
Hi I am trying to export a page to PDF but cannot find a solution that will do this for me :-( I have spent the last 2 days trying, and this has never happened to me! Can anybody help me out here?

I have searched all over the web, and tried about 3 component demos, but none of them work for me!

Hope someone can help - Thanks
When I export a report to MS Word, Word cuts off some of my data on the due to a problem with the margins. I've checked the margins under "page setup" in Access as well as in Word, but for whatever reason, Word won't use the new margin settings.  thanks in advance for your help.

Top Posts