Thursday, December 3, 2020

Print PDF and Export Excel from RDLC in Asp.Net Core

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:



Prerequisites:
1. Asp.Net Core MVC basics
2. Basic RDLC knowledge

Steps To follow:
1. Create an Asp.Net Core 3.1 MVC project
2. Add following Nuget Packages
  •     AspNetCore.Reporting
  •     System.CodeDom
  •     System.Data.SqlClient
3. Modify the Program.cs Class, by making sure it has the below function as:
  public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                    webBuilder.UseWebRoot("wwwroot");
                    webBuilder.UseStartup<Startup>();
                });

4. 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 https://youtu.be/qhcg4dy43xk

5. Move the empty report to your MVC project, into wwwroot/Reports folder, and the dataset to a ReportDataset folder in the MVC project.

6. Configure the dataset and then the RDLC report:




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

7. Create the HomeController in the following way:

 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;

        }

       

    }

8. Then, add the view for the Home controller (Index.cshtml)

<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.

9. The result will be: