Exporting a SQL Server Reporting Services 2005 Report Directly to PDF or Excel

Exporting a SQL Server Reporting Services 2005 (SSRS) Report Directly to PDF/Excel is a handy way of generating high quality reports without being stuck to using the ReportViewer interface. Sometimes the ReportViewer interface is an unnecessary step, but other times the ReportViewer won't render correctly even though the underlying report is correct. This is especially true when your audience might use Firefox or Safari (or anything other than IE), since the ReportViewer control almost never outputs a readable report. Of course it would be nice to just have a button on your page that generates a PDF or Excel file in any browser, and uses a SSRS back-end to do all of the report creating and heavy lifting.

The following code will show how to export such a report, including the passing of an arbitrary number of custom parameters. Note that the identity of the application pool that your website runs under will need to have at least "browser" access to the folder containing the report you want to display. This is usually pretty simple if both the IIS and SSRS server are within the same domain, but it might be tricky if this is not the case.

Microsoft.Reporting.WebForms.ReportViewer rview = new Microsoft.Reporting.WebForms.ReportViewer();
//Web Address of your report server (ex: http://rserver/reportserver)
rview.ServerReport.ReportServerUrl = new Uri(WebConfigurationManager.AppSettings[201DReportServer201D]);
System.Collections.Generic.List<Microsoft.Reporting.WebForms.ReportParameter> paramList = new System.Collections.Generic.List<Microsoft.Reporting.WebForms.ReportParameter>();
paramList.Add(new Microsoft.Reporting.WebForms.ReportParameter(201DParam12033, 201CValue12033));
paramList.Add(new Microsoft.Reporting.WebForms.ReportParameter(201DParam22033, 201CValue22033));
rview.ServerReport.ReportPath = 201C/ReportFolder/ReportName201D;
string mimeType, encoding, extension, deviceInfo;
string[] streamids;
Microsoft.Reporting.WebForms.Warning[] warnings;
string format = 201CPDF201D; //Desired format goes here (PDF, Excel, or Image)
deviceInfo =
201C<DeviceInfo>201D +
201C<SimplePageHeaders>True</SimplePageHeaders>201D +
byte[] bytes = rview.ServerReport.Render(format, deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);
if (format == 201CPDF201D)
Response.ContentType = 201Capplication/pdf201D;
Response.AddHeader(201DContent-disposition201D, 201Cfilename=output.pdf201D);
else if (format == 201CExcel201D)
Response.ContentType = 201Capplication/excel201D;
Response.AddHeader(201DContent-disposition201D, 201Cfilename=output.xls201D);
Response.OutputStream.Write(bytes, 0, bytes.Length);

One potential issue that you might run into upon deploying your project is that your application server may not have the ReportViewer DLLs that are needed. You have two options in this case. The first is to copy the three Microsoft.ReportViewer.*.dll's (ReportViewer.Common.dll, ReportViewer.ProcessingObjectModel.dll, and ReportViewer.WebForms.dll) from your development computer into the BIN folder of your application server (or into the GAC). The second option (though I have not verified it), is to install the SSRS redistributable on the application server (http://www.microsoft.com/downloads/details.aspx?familyid=8a166cac-758d-45c8-b637-dd7726e61367&displaylang=en).

Check out http://www.microsoft.com/sql/technologies/reporting/default.mspx for good SSRS resources, including some nice learning tools and report packs.


  • That wonderful....raely it help me alot.

  • Thanks, this is what I've been looking for. I'll try it and see if it works

  • Scott,

    You could refactor the following lines of code:

    if (format == “PDF”)


    Response.ContentType = “application/pdf”;

    Response.AddHeader(”Content-disposition”, “filename=output.pdf”);


    else if (format == “Excel”)


    Response.ContentType = “application/excel”;

    Response.AddHeader(”Content-disposition”, “filename=output.xls”);


    by using the "mimeType" and "exension" values.
    See my example:

  • I was hoping this code was going to solve a problem I'm having with IE7. We have this code running on a page that was opened with Javascript (in response to a button from another page). But when the content from RS is Excel, the browser window closes immediately. When it's PDF, the window opens fine to show the PDF report.

    Does anyone have any ideas why the browser closes? Scott, is the above code working for you on IE7?

    Thanks for any help.

  • Greg,
    I did just now confirm that the code works for PDF/Excel on IE7 (as well as my normal browser FireFox 2.0). I'm not sure why your browser closes, but it sounds as though the open/save file dialog is the culprit. Since PDF works fine (which is in-browser in your case) there must be a problem when the Excel file attempts to be downloaded. Sorry I can't be more help than that, but hopefully this can get you on track.


  • Great! I did this with ASP sometime back and forgot how in my old age.

  • Anyone have any idea how I can use the script above and have the output file become an email attachment without opening Adobe Reader? Any info would be greatly appreciated!

  • Any thoughts to a VB solution rather than the C# one provided?

  • MissCheeva,
    The report server url is the usually in the form http://rserver/reportserver, which is different from the interface you usually browse to of http://rserver/reports. From there you just add the report path from the root using ServerReport.ReportPath. A good way to test is just to enter the url into your browser and see if the report listing comes up, and then add on the report path and it should render that report.

  • Can we export SRS 2005 reports into Excel 2007

  • @Deepak,
    Natively SSRS 2005 will export to excel 2003 format, but of course this will open just fine in Excel 2007 and can then by converted if desired.

  • This code is great thanks!!!!! :)

  • Excellent posting!

  • Very useful solution - thanks!!

    Do you know if this works if the report server runs in "SharePoint integrated mode"

    And what is the syntax for ReportServer and ReportPath in this scenario??

  • @Morten,
    The full url for a report (like http://server/ReportServer/ReportFolder/ReportName) can be broken down into the report server (http://server/ReportServer) plus path (/ReportFolder/ReportName).

  • Nice. I am trying this code as I type this comment!

    By the way, is there any way to send this attachment to someone else via email in SSRS2005?

    I am trying to create a small application that when user clicks a button to create a report, it generates the report then send it to particular user via email with generated report attached in PDF format.


  • I wonder if you have encountered a similar problem to mine....
    In my case, the browser displays the reports correctly, but upon selecting PDF from the DDL, the built in Microsoft logic creates the PDF, but it loses all leading spaces, tabs, or indentations. Only some of the lines have these, and these lines are usually meant to be headers and are out of alignment.

    The same ting happens when I use your code example... all leading spaces, tabs, or indentations are lost and data is misaligned.

    Thanks in advance for any iinsight.

  • This works great. Any way to automatically save to a specified directory instead of being bothered with the open/save/cancel dialog??

  • What no one seems to know how to do is, have the report print DIRECTLY to a printer. I don't want the report to ever popup anywhere. I want 60 reports to automatically print out to a printer after a used presses 1 button in a .net app. Sigh :(

  • @QuestionDude,
    I actually don't think it is even possible to print directly in any .NET app without something like an ActiveX plug-in. This is actually a good thing though -- image the junk you would get if instead of launching popups, web apps were able to directly print things to your printer without user intervention.

  • You can print directly by setting up a subscription on the report server.

  • Is there any way to do this silently w/o the save dialog showing up?

  • In SSRS How can get report in a stream format without a report viewer and without form.I am using C# .I need create some class to get report a stream format without a report viewer and without form

  • @Thuy,
    As long as you set your Content-disposition to filename=fname instead of attachment=fname then the file can open directly in the browser (if you are using PDF).

    The only way to get a stream from a report server is to use the report viewer, but I don't see the problem because the report viewer can be created in code and the user never needs to see what's going on in the background.

  • I am in C#
    Any idea how to create report viewer in code?

  • @Jane,
    This post explains how to create a report viewer in code -- notice the first line: Microsoft.Reporting.WebForms.ReportViewer rview = new Microsoft.Reporting.WebForms.ReportViewer(); If you actually want to display out the report in the report viewer, you can add it to your page's control tree or create it as a native control.

  • Where do you supposed to put the code?


  • Any idea how I could code this in VB.Net?

  • I have several images mixed in with the text in my report. They look very jagged in the pdf. When displayed in a ReportViewer control on a web page they look fine. When I manually export them from the ReportViewer to Excel or a Web Archive they look fine.

    Have tried them as jpgs, bmps, and pngs with similar results. How can you get a smooth-looking image into a pdf from ReportViewer?

  • Another way to open a pdf or excel is on a button click event add the following redirect:


    the format can be PDF or Excel and send the report directly to the desired format.

  • The above code works great, however is there a way to export multiple reports to an Excel file, with each report having it's own tab?
    I want the user to be able to select one or more reports, hit a button and the result is one Excel file containing all the reports run.

  • Hi,
    I want to export to PDF an report with params, Do you have any idea?

    sorry, but I tried it, and i can't

  • Hi,

    I want to export to PDF an report with params, Do you have any idea?

    sorry, but I tried it, and i can't


  • Hola
    para este mensaje


    I want to export to PDF an report with params, Do you have any idea?

    sorry, but I tried it, and i can't


    Donde WRCustomers es el nombre del webservice

    Dim RSGuardar As New WRCustomers.ReportExecutionService

    Dim WRParam(0) As WRCustomers.ParameterValue
    WRParam(0) = New WRCustomers.ParameterValue()
    WRParam(0).Name = "Estato"
    WRParam(0).Value = "6578"

    ' Cargo el report.
    RSGuardar.LoadReport(Me.ReportViewer1.ServerReport.ReportPath, historyID)
    RSGuardar.SetExecutionParameters(WRParam, "es-mx")

  • Thanx a lot
    Works like charm
    Any Idea how to this exported report attach to e mail and send
    to someone.

  • I want to export SRS 2005 reports exactly into Excel 2007. Because the report that I generate contains much more information than it is possible to fit in Excel 2003. can anyone help me?.. thanks

  • Has anyone tested this code using SSRS 2000?

  • Does anyone have this code on visual basic??

  • Dim rview As New Microsoft.Reporting.WebForms.ReportViewer()
    'Web Address of your report server (ex: http:'rserver/reportserver)
    ' I used AppSettingsReader instead of WebConfigurationManager class
    Dim apr As New AppSettingsReader()
    rview.ServerReport.ReportServerUrl = New Uri(apr.GetValue("ReportServer", GetType(String)))
    Dim paramList As New System.Collections.Generic.List(Of Microsoft.Reporting.WebForms.ReportParameter)
    ' set your parameters
    paramList.Add(New Microsoft.Reporting.WebForms.ReportParameter("Param1", "Value1"))
    paramList.Add(New Microsoft.Reporting.WebForms.ReportParameter("Param2", "Value2"))
    ' set the name of the reportPath
    rview.ServerReport.ReportPath = "/ReportFolder/ReportName"

    Dim mimeType As String = Nothing
    Dim encoding As String = Nothing
    Dim extension As String = Nothing
    Dim deviceInfo As String = Nothing
    Dim streamids As String() = Nothing
    Dim warnings As Microsoft.Reporting.WebForms.Warning() = Nothing
    Dim format As String = "PDF" 'Desired format goes here (PDF, Excel, or Image)

    deviceInfo = "True"

    Dim bytes As Byte() = rview.ServerReport.Render(format, deviceInfo, mimeType, encoding, extension, streamids, warnings)
    If format = "PDF" Then
    Response.ContentType = "application/pdf"
    Response.AddHeader("Content-disposition", "filename=output.pdf")
    ElseIf format = "Excel" Then
    Response.ContentType = "application/excel"
    Response.AddHeader("Content-disposition", "filename=output.xls")
    End If
    Response.OutputStream.Write(bytes, 0, bytes.Length)

  • Is that possible to send the report in mail as an atachment from SQL?

    I have a report I want to mail it through a cheduling by creating a Job and chedule the report, is this possible?

    If yes, could please send me the code or link.

    Ali Adravi

  • Can this work for CSV files as well? Also, thie code below opens the CSV file in the browser. Any way to get it to go directly to file or to a file Save As... dialog?

    string rptServer = ConfigurationManager.AppSettings.Get("ReportServerURL");
    string rptPath = "?/IRIS_Reports/ExportMain";
    string rptOptions = "&rs:Command=Render&rc:Format=CSV&rc:Toolbar=False&rc:Encoding=ASCII&rs:ClearSession=true";
    string rptPrintWhat = "&PrintWhat=" + PrintWhat + "&RecordID=" + _globals.MasterRecordID;

    string cmd = rptServer + rptPath + rptOptions + rptPrintWhat;

    Response.ContentType = "text/x-plain";
    Response.AddHeader("Content-disposition", "filename=output.csv");

  • Remove "Response.ContentType" line and "Response.Addheader" line, both useless.

    Change "rc:Format=CSV" to "rs:Format=CSV" and it doesn't display in the browser anymore. But, it creates a 0-byte file.

  • This code was of great help ..thank you

  • problem whith exporting tiff files usu=ing samecode

  • Hi This great article. Is there any code for word re-endering

  • Response to the 'how to email attached pdf and xls - using concepts introduced on this page.'

    I have not been able to identify a straightforward method to augment this code and email the displayed PDF.

    One way you may want to consider is utilizing the SSRS scheduled emailing functions of the SSRS server. Choosing the report, creating a schedule, and setting recipents is easy enough for the set schedule and recipient list, but how for something dynamic?

    This is done in three steps:
    1) set up a schedule under the 'site settings' page, to execute a report object every X minutes (10?)
    2) create a new subscription. on the third page of the subscription setup, point to the table that will contain the records for the input parameters to the report to be emailed. The trick is to dynamically add records to this when a user clicks a link ( notifying the user, "you will receive the report via email with X minutes.)
    3) create a job that clears the table form the datadriven step of the subscription every X minutes, but on a interval that is shifted a certain time.

    The logistics will need to be verified, but I got somethign like this working. it is important to - make sure do not clear out any pending subscriptions, and make sure you the records before the scheduled job starts.

  • Does anybody know how to make the print dialog box pop up automatically after the pdf is displayed?

  • Thanks. the concept is excellent...

  • It works fine for me however I want to set export directory path.

  • I have a report for individaul employee. Now, from application if user selects multiple employees then i want to save the report for each employee in saperate pdf.
    How can i save the reports directly without prompting the Save dialog box for each report?

    Another approach i could take is to get a single PDF file containing each employee report on saperate page so that user can print this file and distribute the report to individuals.

  • What is the Work of deviceInfovariable ??

  • 01.Dim returnValue as byte()
    02.Dim mimeType As String = ""
    03.Dim returnValue As Byte()
    04.Dim encoding As String = ""
    05.Dim streams As String()
    06.Dim warnings As Microsoft.Reporting.WebForms.Warning()
    09.If Request.Params("exportformat") "" Then
    10.returnValue = ReportViewer.ServerReport.Render(
    18.Response.Buffer = True
    21.Response.ContentType = mimeType
    25."attachment;filename=" +
    26.Request.Params("ReportName") +
    27."." + Request.Params("exportformat")
    33.End If

  • Please let me know where to write this code. I am getting error at response(Element not found) at resopnse.clear() when i added this code to a .cs class file in ASP.net application. Please let me know where i should write this code and references to be added to include Response.

  • I would like to know the location where to add this code for my report.


  • Just question, is there an add on for Excel / PDF export or has it to be the way described above?

  • Thanks a lot, this is useful.

  • Hi Guys,

    Can any body help me out... I got a one Task in my office. It's a big challenge to me. The task is SQLServer output should store in .txt and .pdf format in automatically for every one hour. then the same output is .txt send as SMS and .pdf format should sent as the email should sent as automatically for every 1hour....

  • I all the time emailed this weblog post page to all my associates, since if like
    to read it after that my friends will too.

  • can anybody tell me how to use this code step by step

  • Nice post. I learn something totally new and challenging on websites I stumbleupon every day.
    It will always be useful to read through content from other authors
    and practice a little something from other web sites.

  • I every time used to read article in news papers but now as I am a
    user of net therefore from now I am using net for articles, thanks to web.

  • Hi there, just became alert to your blog through Google, and found that
    it's truly informative. I am gonna watch out for brussels. I will be grateful if you continue this in future. A lot of people will be benefited from your writing. Cheers!

  • Somebody essentially assist to make severely articles I'd state. That is the very first time I frequented your website page and to this point? I amazed with the research you made to create this actual post extraordinary. Excellent job!

  • Hello, yup this piece of writing is genuinely nice and I have learned lot of things from it on the topic of blogging.

  • An impressive share! I've just forwarded this onto a colleague who was conducting a little research on this. And he actually bought me breakfast because I found it for him... lol. So allow me to reword this.... Thanks for the meal!! But yeah, thanks for spending the time to discuss this topic here on your website.

  • Greetings! Very useful advice within this post!
    It's the little changes which will make the greatest changes. Many thanks for sharing!

  • I got this website from my pal who shared with me about this website
    and at the moment this time I am visiting this web site and reading very informative posts here.

  • That is really fascinating, You're an excessively skilled blogger. I've joined your feed
    and sit up for in search of more of your wonderful
    post. Additionally, I have shared your web site in my
    social networks

  • Having read this I thought it was rather informative.
    I appreciate you spending some time and effort to put this information together.
    I once again find myself personally spending a significant amount of time both reading and posting
    comments. But so what, it was still worth it!

  • Hi,

    Thanks for your article. I am using your code in my MVC3 project. I am getting the following exception in my aspx page,

    BinaryWrite exception “OutputStream is not available when a custom TextWriter is used”

    in the following line,

    Response.OutputStream.Write(bytes, 0, bytes.Length);

    Could you help on this issue...?

Comments have been disabled for this content.