Monday, February 13, 2012

Export to pdf/excel/word/csv/txt from DataTable/DataGrid in asp.net

Note: When you export the GridView to PDF using the below code it will seem that the export is taking place correctly but when you try to open the file you will realize that the file is corrupted. Although this particular code works when exporting to Excel or Text files this code will fail when exporting to PDF files. To export GridView to PDF we will need to use a third party library ITextSharp:  http://funwithcomputers-nishant.blogspot.in/2011/11/export-gridview-to-pdf-using-itextsharp.html   (or)  http://highoncoding.com/Articles/483_Exporting_GridView_to_PDF_Document.aspx

DataGrid dtaFinal = new DataGrid();
dtaFinal.DataSource = dsReports.Tables[0];
dtaFinal.DataBind();

dtaFinal.HeaderStyle.ForeColor = System.Drawing.Color.White;
dtaFinal.HeaderStyle.BackColor = System.Drawing.Color.DarkGray;
dtaFinal.ItemStyle.BackColor = System.Drawing.Color.White;
dtaFinal.AlternatingItemStyle.BackColor = System.Drawing.Color.AliceBlue;


//---Create the File---------
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();

//---For PDF uncomment the following lines----------
//Response.ContentType = "application/pdf";
//Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");

//---For MS Excel uncomment the following lines----------
//Response.ContentType = "application/vnd.ms-excel";
//Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

//---For MS Word uncomment the following lines----------
//Response.ContentType = "application/vnd.word";
//Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");

//---For CSV uncomment the following lines----------
//Response.ContentType = "text/csv";
//Response.AddHeader("content-disposition", "attachment;filename=FileName.csv");

//---For TXT uncomment the following lines----------
//Response.ContentType = "text/plain";
//Response.AddHeader("content-disposition", "attachment;filename=FileName.txt");


EnableViewState = false;

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

//---Renders the DataGrid and then dumps it into the HtmlTextWriter Control
dtaFinal.RenderControl(hw);

//---Utilize the Response Object to write the StringWriter to the page
Response.Write(sw.ToString());
Response.Flush();
Response.Close();
Response.End();

No comments:

Post a Comment