When you’re working with ASP.NET (C#) and the ReportViewer control, you will probably want to export that report as CSV or Excel (programmatically).

Here’s a snippet of what I’ve used. Simply call the method and voila, you’ll be asked to download the file.

Export(ReportViewer1, “CSV”);
Export(ReportViewer1, “XLS”);

      public bool Export(ReportViewer viewer, string exportType)
        {
            Warning[] warnings = null;
            string[] streamIds = null;
            string mimeType = string.Empty;
            string encoding = string.Empty;
            string extension = string.Empty;
            string deviceInfo = string.Empty;
            string filetype = string.Empty;
            string reportsTitle = GetReportTitle(viewer); // just gets the Report title... make your own method

            //ReportViewer needs a specific type (not always the same as the extension)
            if (exportType == "XLS")
            {
                filetype = "Excel";
            }
            else
            {
                filetype = exportType;
            }

            byte[] bytes = viewer.ServerReport.Render(filetype, null, // deviceinfo not needed for csv
                out mimeType, out encoding, out extension, out streamIds, out warnings);

            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Clear();

            System.Web.HttpContext.Current.Response.ContentType = mimeType;
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + reportsTitle + "." + exportType);

            System.Web.HttpContext.Current.Response.BinaryWrite(bytes);

            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();

            return true;
        }

It would be incredibly easy to turn this into a class, that can do a whole bunch of different formats. It’s very easy to turn this code into exporting a PDF document — but it’s a wee bit different.

To select which format I wanted a report to be exported as, I used the following:

Markup:

                        <asp:DropDownList id="DropDownListExport" runat="server" >
                             <asp:ListItem Value="XLS">Excel</asp:ListItem>
                             <asp:ListItem Value="CSV">CSV</asp:ListItem>
                        </asp:DropDownList>
                        <asp:Button id="Button1"  Text="Export" OnClick="Export_Click" runat="server"/>

Code-behind:

        public void Export_Click(object sender, EventArgs e)
        {
            string type = DropDownListExport.SelectedItem.Value;

            Export(type, ReportViewer1);
        }

If you’d like any help regarding this, leave a comment.

Tags: , , , , , , , ,

· · · ◊ ◊ ◊ · · ·