May 03, 2008

Export ReportViewer Report to PDF, Excel, HTML

The following code helps exporting the Report into PDF and Excel formats using the Render method of the ServerReport. Use below code after the report is loaded (refresh() is called on the reportviewer control).

1 string mimeType;
2 string encoding;
3 string fileNameExtension;
4 Warning[] warnings;
5 string[] streamids;
6 byte[] exportBytes = reportViewer.ServerReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings);
7 HttpContext.Current.Response.Buffer = true;
8 HttpContext.Current.Response.Clear();
9 HttpContext.Current.Response.ContentType = mimeType;
10 HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedReport." + fileNameExtension);
11 HttpContext.Current.Response.BinaryWrite(exportBytes);
12 HttpContext.Current.Response.Flush();
13 HttpContext.Current.Response.End();


To get Excel file use "Excel" as the parameter in the Render method.

Sometimes you might need to send the Report content into email. To Achieve this you can use the above code where you need to pass "HTML4.0" as the first parameter to the Render method. After you get the byte array from the Render method you can convert it to string as below


1 string mimeType;
2 string encoding;
3 Warning[] warnings;
4 string[] streamids;
5 string fileNameExtension;
6 byte[] htmlBytes = MyReportViewer.ServerReport.Render("HTML4.0", null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings);
7 string reportHtml = System.Text.Encoding.UTF8.GetString(htmlBytes);
8 return reportHtml;

Enjoy......

Submit this story to DotNetKicks

2 comments:

Timothy said...

This was really good as I found it really helpful. Also is there a way to do the same thing with a windows application?

Michael said...

Thank you very much for your post.

I really needed to make a localreport rendering html. works like a charm.

Thanks again!