Monday, March 17, 2014

Using RDLC with ASP.Net MVC to export report in PDF/Excel format

To export a report in PDF/Excel format using RDLC.


  1. Create a ASP.Net MVC web site.
  2. Add a RDLC report and creates its DataSources and Design the report as per requirement.
  3. Create an action method in your controller and use following code.

public ActionResult GetPdfReport(int month, int year, int snapshottypeid, long taskrunid)
{

//Step 1 : Create a Local Report.
LocalReport localReport = new LocalReport();

//Step 2 : Specify Report Path.
localReport.ReportPath = Server.MapPath("~/Content/UnAssignedLevelsReport.rdlc");

//Step 3 : Create Report DataSources
ReportDataSource dsUnAssignedLevels = new ReportDataSource();
dsUnAssignedLevels.Name = "UnAssignedLevels";
dsUnAssignedLevels.Value = dataSet.UnAssignedLevels;

ReportDataSource dsReportInfo= new ReportDataSource();
dsReportInfo.Name = "ReportInfo";
dsReportInfo.Value = dataSet.ReportInfo;

//Step 4 : Bind DataSources into Report
localReport.DataSources.Add(dsUnAssignedLevels);
localReport.DataSources.Add(dsReportInfo);

//Step 5 : Call render method on local Report to generate report contents in Bytes array
string deviceInfo = "<DeviceInfo>" +
"  <OutputFormat>PDF</OutputFormat>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
string mimeType;
byte[] renderedBytes;
string encoding;
string fileNameExtension;
//Render the report          
renderedBytes = localReport.Render("PDF", deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);


//Step 6 : Set Response header to pass filename that will be used while saving report.
Response.AddHeader("Content-Disposition",
"attachment; filename=UnAssignedLevels.pdf");

//Step 7 : Return file content result
return new  FileContentResult(renderedBytes, mimeType);
}

4. While deploying code to a development/production server make sure following assemblies are referred from correct location and for them set CopyLocals as True.