Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Custom Export to Excel for ReportViewer (rdlc)

I'm interested in creating a custom Export to Excel option for my Report in ReportViewer. This is mostly because I want pdf disalbed and I did that via:

 ReportViewer1.ShowExportControls = false;

Since there is no way to disable any specific export functionality (e.g. pdf but not excel) in ReportViewer. Here's my (slightly) modified code below. Ideally I would like something similar to the previous Export options where I can save the file to whatever location I want.

EDIT: The code works but how would I need to modify the Filestream so that instead of having the file get saved automatically I can prompt the user so that they can save to whichever location they want?

protected void btnExportExcel_Click(object sender, EventArgs e)
{
    Warning[] warnings;
    string[] streamids;
    string mimeType;
    string encoding;
    string extension;

    byte[] bytes = ReportViewer1.LocalReport.Render(
       "Excel", null, out mimeType, out encoding,
        out extension,
       out streamids, out warnings);

    FileStream fs = new FileStream(@"c:\output.xls",
       FileMode.Create);
    fs.Write(bytes, 0, bytes.Length);
    fs.Close();

}
like image 898
firedrawndagger Avatar asked Aug 16 '10 14:08

firedrawndagger


2 Answers

Just a heads up... the accepted answer will render as an XLS file, which was requested by the original poster.

However, you can now export to XLSX as well. You have to change the format parameter of the Render() method from "Excel" to "EXCELOPENXML".

To get a full list of possible values you can call ReportViewer1.LocalReport.ListRenderingExtensions(). When I ran it on my report viewer instance I got these possible options:

"Excel" "EXCELOPENXML" "IMAGE" "PDF" "WORD" "WORDOPENXML"

I found it very hard to determine what you needed to pass in for the formats. MSDN documents this very poorly if you ask me.

like image 149
JBausmer Avatar answered Sep 18 '22 18:09

JBausmer


I put this together based on Microsoft's documentation on ReportViewer and some Google searches in case anyone runs into the issue similar to mine:

protected void ExportExcel_Click(object sender, EventArgs e)
{
    Warning[] warnings;
    string[] streamids;
    string mimeType;
    string encoding;
    string extension;
    string filename;

    byte[] bytes = ReportViewer1.LocalReport.Render(
       "Excel", null, out mimeType, out encoding,
        out extension,
       out streamids, out warnings);

    filename = string.Format("{0}.{1}", "ExportToExcel", "xls");
    Response.ClearHeaders();
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    Response.ContentType = mimeType;
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}
like image 31
firedrawndagger Avatar answered Sep 20 '22 18:09

firedrawndagger