Monday, February 1, 2010

How To: Execute and Save SSRS Report using C#

It is often required to execute a SSRS report from within C# and save it in the required file format like PDF, XLS etc.

SQL Server Reporting Services (SSRS) exposes two web services using which we can execute a report and save it in the required file format. The two web services are:

  • Reporting Service 2005 : http://[SERVER]/reportserver/reportservice2005.asmx
  • Report Execution Service : http://[SERVER]/reportserver/reportexecution2005.asmx

Add the above two web services as "Web Reference" to your project with the following namespace RS2005 and RE2005:

Use the C# code below to execute and save the report:

      public static void SaveReport()

RS2005.ReportingService2005 rs;
RE2005.ReportExecutionService rsExec;

// Create a new proxy to the web service
rs = new RS2005.ReportingService2005();
rsExec = new RE2005.ReportExecutionService();

// Authenticate to the Web service using Windows credentials
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;

rs.Url = "http://<SERVER>/reportserver/reportservice2005.asmx";
rsExec.Url = "http://<SERVER>/reportserver/reportexecution2005.asmx";

string historyID = null;
string deviceInfo = null;
string format = "EXCEL";
Byte[] results;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
RE2005.Warning[] warnings = null;
string[] streamIDs = null;

// Path of the Report - XLS, PDF etc.
string fileName = @"c:\samplereport.xls";
// Name of the report - Please note this is not the RDL file.
string _reportName = @"/Marketing_Report";
string _historyID = null;
bool _forRendering = false;
RS2005.ParameterValue[] _values = null;
RS2005.DataSourceCredentials[] _credentials = null;
RS2005.ReportParameter[] _parameters = null;

_parameters = rs.GetReportParameters(_reportName, _historyID, _forRendering, _values, _credentials);
RE2005.ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID);
RE2005.ParameterValue[] parameters = new RE2005.ParameterValue[1];

if (_parameters.Length > 0)
//parameters[0] = new RE2005.ParameterValue();
//parameters[0].Label = "";
//parameters[0].Name = "";
//parameters[0].Value = "";
rsExec.SetExecutionParameters(parameters, "en-us");

results = rsExec.Render(format, deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);

using (FileStream stream = File.OpenWrite(fileName))
stream.Write(results, 0, results.Length);
catch (Exception ex)
throw ex;


Following output file formats are available: XML, CSV, IMAGE, PDF, EXCEL, WORD, HTML 4.0 and MHTML

Hope this helps!