Monday, May 31, 2010

Report Viewer Control: Exporting Reports to Word, PDF and Excel Programmatically

When Reporting Services reports are shown with ASP.NET Report Viewer control, one of the common requirements for exporting facility is, limiting it to few output formats. By default Export drop-down contains 7 output formats. If we need to limit for 1-2 output formats, one way is, hide the ExportControl and implement it with our own code. Here is the way of implementing it;

Here is a sample screen for a ASP.NET page with Reporting Services report. Note that ExportControl is hidden in the toolbar and drop-down is added to show output formats for exporting.

Untitled

Here is the code of Page_Load.

protected void Page_Load(object sender, EventArgs e)
{
    ReportViewer1.ShowExportControls = false;
    ReportViewer1.ProcessingMode = ProcessingMode.Remote;
 
    // this can be set with control itself.
    //ReportViewer1.ServerReport.ReportServerUrl = new Uri(@"http://localhost/reportserver");
    //ReportViewer1.ServerReport.ReportPath = @"/Report Project1/Report2";
 
    if (!IsPostBack)
    {
        DropDownList1.Items.Add(new ListItem("Word", "Word"));
        DropDownList1.Items.Add(new ListItem("Excel", "Excel"));
        DropDownList1.Items.Add(new ListItem("Acrobat (PDF) file", "PDF"));
 
    }
}

Here is the code for Button-Click.

protected void Button1_Click(object sender, EventArgs e)
{
    string mimeType;
    string encoding;
    string fileNameExtension;
    string[] streams;
    Warning[] warnings;
    
    byte[] bytes = ReportViewer1.ServerReport.Render(DropDownList1.SelectedValue, null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = mimeType;
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SalesReport." + fileNameExtension);
    HttpContext.Current.Response.BinaryWrite(bytes);
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();
}

If you need to find out other output formats and control related info, visit http://msdn.microsoft.com/en-us/library/ms345248.aspx.

This explains ServerReport.Render method: http://msdn.microsoft.com/en-us/library/ms252214(VS.80).aspx.

No comments:

Post a Comment