Skip to main content

Report generation in .Net Core API

 In this tutorial we will learn about quick way to generate reports using .net core api. When we work in companies, we may face a situation where client ask to generate reports, and he is not ready to spend money in purchasing third party libraries to get reports. Apart from this he want to work to done in same day or he has some urgency.

In this situation this tutorial will helpful where we need to generate reports in single day without spending and wasting time in research.

Let’s Start.

b. Create Endpoint for Download file

c. Make a call to database and fetch data.

d. Create report in html format and send html file back to user as response.

Consider we connect to database and get below data table

Consider code below

using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DownloadFile.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DownloadFile : ControllerBase
{
// GET: api/<DownloadFile>
[HttpGet]
public ActionResult GetFileDownload()
{
DataTable dt = GetDataFromDatabase();
string HtmlBody = ExportDatatableToHtml(dt);

var contentType = "text/xml";
var bytes = Encoding.UTF8.GetBytes(HtmlBody);
var result = new FileContentResult(bytes, contentType);
result.FileDownloadName = "Report.html";
return result;

}

protected string ExportDatatableToHtml(DataTable dt)
{
/// using html code we are creating html file and printing datatable.
StringBuilder strHTMLBuilder = new StringBuilder();
strHTMLBuilder.Append("<html >");
strHTMLBuilder.Append("<head>");
strHTMLBuilder.Append("</head>");
strHTMLBuilder.Append("<body>");
strHTMLBuilder.Append("<table border='1px' cellpadding='1' cellspacing='1' bgcolor='lightyellow' style='font-family:Garamond; font-size:smaller'>");
strHTMLBuilder.Append("<tr >");
foreach (DataColumn myColumn in dt.Columns)
{
strHTMLBuilder.Append("<td >");
strHTMLBuilder.Append(myColumn.ColumnName);
strHTMLBuilder.Append("</td>");
}
strHTMLBuilder.Append("</tr>");

foreach (DataRow myRow in dt.Rows)
{
strHTMLBuilder.Append("<tr >");
foreach (DataColumn myColumn in dt.Columns)
{
strHTMLBuilder.Append("<td >");
strHTMLBuilder.Append(myRow[myColumn.ColumnName].ToString());
strHTMLBuilder.Append("</td>");
}
strHTMLBuilder.Append("</tr>");
}
//Close tags.
strHTMLBuilder.Append("</table>");
strHTMLBuilder.Append("</body>");
strHTMLBuilder.Append("</html>");
string Htmltext = strHTMLBuilder.ToString();
return Htmltext;
}

private DataTable GetDataFromDatabase()
{
// make call to database int this case we hadcoded datatable.

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("NAME", typeof(string));
table.Columns.Add("CITY", typeof(string));

table.Rows.Add(111, "Devesh", "Ghaziabad");
table.Rows.Add(222, "Nikhil", "United State");
table.Rows.Add(102, "himanshu", "Canada");
table.Rows.Add(456, "Kapil", "Dubai");
table.Rows.Add(3345, "Sanjay", "Germany");

return table;
}

}
}

Understanding code.

a. We have created GetFileDownload() Endpoint

b. We are making call to database function name -> GetDataFromDatabase , in real time use case please replace hard coded datatable with actual data from database.

c. We have created Function to convert Datatable to HTML file

d. We are iterating each row of datatable and formatting rows and columns using very simple tr and td tags.

e. Download code has FileContentResult Which inherits from ActionResult. we are converting html string into bytes and encapsulating bytes into FileContentResult class and returning as result

Running application

Click Download API.

we will get file from code.

Download file.

Open File. We have opened file in browser.

We are ready with report.

Conclusion


Comments

Popular posts from this blog

Design Application using Clean Architecture

  Clean Architecture , introduced by  Robert C. Martin   (Uncle Bob), aims to create systems that are: Independent of frameworks Testable Independent of UI Independent of database Independent of any external agency Clean Architecture emphasizes separating the concerns of different parts of the system and ensuring that each part has a clear responsibility. .NET clean architecture as a development approach, available in a layered form to reduce dependency. The architecture consists of several layers, each with a specific role and dependencies that flow in one direction: from the outer layers to the inner layers. Inner most Layer is independent to its outer layer, means inner most layer does not have any references, it builds and stand independently. Dependency Rule The core principle of Clean Architecture is the  Dependency Rule , which states that source code dependencies can only point inward.  This means: Nothing in inner circle can depend on anything in an out...

How to Earn online from Medium.com

  As freelancer I started writing on medium (Tech blogs) from  Aug 2024   but I was already writing tech blogs on c-sharpcorner.com “The purpose of this post is to encourage new writers by helping them understand how they can earn as freelancers.” “Medium is a great platform for writers. When I started writing, I had no idea that I would reach the $100 benchmark in just four months. Now, I’m feeling self-inspired, as it has become a valuable source of income as a freelancer.” AUG 2024 ( $0 ) It was just beginning, and I posted 4 articles and had only few views 455 and 165 reads. During this time, I was learning about medium rules for writers and partner program. It will take some time to understand over all process. SEP 2024 ($6) As I started writing and I was getting few cents on Aug 2024, I posted 8 more articles in SEP, and it was good month because my blogs were getting noticed and I started getting claps etc. “This month, I went from $0 to $6, which was an achievemen...

Fixing High CPU Usage in .NET Core using Parallelism

  We will fix problem occurs due to incorrect use Parallelism in .NET Core To increase application performance sometimes we use process task or work extensively in Parallel and that may lead performance issue. When we do code, we should understand our requirement very carefully along with hardware resources those we have. We should code like that there should be less CPU usage and server should work without issues. In .NET Core, when you’re using parallelism (like Parallel.For, Task.WhenAll, or Task.Run), you might encounter performance issues if the number of concurrent threads or tasks exceeds what your system can efficiently handle. A common issue is high CPU usage or resource contention, which can degrade overall performance, cause excessive context switching, and even lead to thread starvation or deadlocks. Non members can access from here Effective Parallelism Strategies to Mitigate High CPU Usage in .NET Core We will fix problem occurs due to incorrect use Parallelism in .NE...