Often a business requirement to share information in these formats.
Firstly Excel export:
|
|
Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + table.DisplayName + ".xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; StringWriter StringWriter = new System.IO.StringWriter(); HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter); GridView1.RenderControl(HtmlTextWriter); String parsed = StringWriter.ToString().Replace("<a", "<div style=\"font-weight:bold;\"").Replace("</a>", "</div>"); if (parsed.Contains("<tr class=\"DDFooter\">")) { parsed = parsed.Remove(parsed.IndexOf("<tr class=\"DDFooter\">"), (parsed.LastIndexOf("</tr>") - parsed.IndexOf("<tr class=\"DDFooter\">")) + 5); } Response.Write(parsed); Response.End(); |
You can change table.DisplayName to what you want your file to be named and remove the following if you are not using a Dynamic Data site:
|
|
if (parsed.Contains("<tr class=\"DDFooter\">")) { parsed = parsed.Remove(parsed.IndexOf("<tr class=\"DDFooter\">"), (parsed.LastIndexOf("</tr>") - parsed.IndexOf("<tr class=\"DDFooter\">")) + 5); } |
For PDF export:
I used iTextSharp for this with the following usings:
|
|
using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html.simpleparser; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + table.DisplayName + ".pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.DataBind(); GridView1.RenderControl(hw); StringReader sr = new StringReader("sw.ToString().Replace("<a", "<div style=\"font-weight:bold;\"").Replace("</a>", "</div>")); String sr_string = sr.ReadToEnd(); if (sr_string.Contains("<tr class=\"DDFooter\">")) { sr = new StringReader(sr_string.Remove(sr_string.IndexOf("<tr class=\"DDFooter\">"), (sr_string.LastIndexOf("</tr>") - sr_string.IndexOf("<tr class=\"DDFooter\">")) + 5)); } Document pdfDoc = new Document(PageSize.A4.Rotate(), 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(); |
Again if you are not using a Dynamic Data site, you may not need to replace the <a> tags but iTextSharp seems to dislike them and will throw errors.
Notes:
- You may have to set EnableEventValidation=”false” on your ASPX page. This was fine for me internally but on something public facing you may want to look into work arounds.
- You may need to register your controls for post-back like:
|
|
ScriptManager scriptManager = ScriptManager.GetCurrent(Page); scriptManager.RegisterPostBackControl(pdf); scriptManager.RegisterPostBackControl(excel); |