Saturday, June 14, 2008

Export ASP.NET page to Word, Excel or HTML

If u want to Export your .NET aspx page to Word, Excel or Html, then you just change the ContentType of the Response object and overriding the RenderControl method of the control.

Here is the code for “Export ASP.NET page to Word, Excel or html. “

Firstly, you will
import System.IO

Imports System.IO

After this you will write below code


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)
///
this.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();

No comments: