Print PDF and Export Excel from RDLC in Asp.Net Core
Tags: dotnet, tutorial, csharp
Published: 2020-12-03 11:54:51

This blog post is providing some more insight and the source code to a youtube tutorial, that I consider being worthwile looking at more closely.

Original Youtube video that inspired me: 
{% youtube AglE-xgmbY8 %}

*Github code repo:* https://github.com/zoltanhalasz/CoreRDLCReport.git
*Live sample application:* https://rdlc-aspnetcore.zoltanhalasz.net/

**Prerequisites:**
* Asp.Net Core MVC basics
* Basic RDLC knowledge

**Steps To follow:**
* Create an Asp.Net Core 3.1 MVC project
* Add following Nuget Packages:
    "AspNetCore.Reporting",
    "System.CodeDom",
    "System.Data.SqlClient"
* Modify the Program.cs Class, by making sure it has the below function as:
```csharp
  public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                    webBuilder.UseWebRoot("wwwroot");
                    webBuilder.UseStartup<Startup>();
                });
```
* Add a new project to the existing solution, a WinForm application. Create an empty RDLC report there, and also a DataSet for the report.

If your Visual Studio does not include the extension for RDLC reports, please take a look 
{% youtube qhcg4dy43xk %}
* Move the empty report to your MVC project, into wwwroot/Reports folder, and the dataset to a ReportDataset folder in the MVC project.

* Configure the dataset and then the RDLC report:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wlacl24gtks4zrarkdtu.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qox30no755ykq7a81bvw.png)

The above report will have a string (text parameter) "prm" in it.

* Create the HomeController in the following way:
```csharp
public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly IWebHostEnvironment _webHostEnvironment;

        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment)
        {
            _logger = logger;
            _webHostEnvironment = webHostEnvironment;
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Print()
        {
            var dt = new DataTable();
            dt = GetEmployeeList();
            string mimetype = "";
            int extension = 1;
            var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Employees.rdlc";
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("prm", "RDLC report (Set as parameter)");
            LocalReport lr = new LocalReport(path);
            lr.AddDataSource("dsEmployee", dt);
            var result = lr.Execute(RenderType.Pdf, extension, parameters, mimetype);
            return File(result.MainStream,"application/pdf");
        }

        public IActionResult Export()
        {
            var dt = new DataTable();
            dt = GetEmployeeList();
            string mimetype = "";
            int extension = 1;
            var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Employees.rdlc";
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("prm", "RDLC report (Set as parameter)");
            LocalReport lr = new LocalReport(path);
            lr.AddDataSource("dsEmployee", dt);
            var result = lr.Execute(RenderType.Excel, extension, parameters, mimetype);
            return File(result.MainStream, "application/msexcel", "Export.xls");
        }
        private DataTable GetEmployeeList()
        {
            var dt = new DataTable();
            dt.Columns.Add("EmpId");
            dt.Columns.Add("EmpName");
            dt.Columns.Add("Department");
            dt.Columns.Add("BirthDate");
            DataRow row;

            for (int i = 1; i< 100; i++)
            {
                row = dt.NewRow();
                row["EmpId"] = i;
                row["EmpName"] = i.ToString() + " Empl";
                row["Department"] = "XXYY";
                row["BirthDate"] = DateTime.Now.AddDays(-10000);
                dt.Rows.Add(row);
            }
            return dt;
        }
       
    }
```
* Then, add the view for the Home controller (Index.cshtml)
```html
<div class="text-center">
    <h1 class="display-4">RDLC Print</h1>
    <div>
        <a href="../home/print" target="_blank" class="btn btn-primary">Print PDF</a>
        <a href="../home/export" target="_blank" class="btn btn-secondary">Export Excel</a>
    </div>
</div>
```
This will generate PDF and export excel, based on the dummy data we populated the report.
* The result will be:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1ol7qdhl85u0g8vc2au7.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3e1g5fxduw5pbaw8b9ks.png)