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

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

Architecting Resilient .NET Core Applications: Handling Transient Failures.

  Transient Failures happen when server is temporarily overloaded.  We need to handle this instead of sending response back to client and say like that “Server is not responding” In the world of Cloud there are temporary failures that may occur in a system and can be recovered from by retrying the operation. T hese failures typically occur due to network issues, temporary unavailability of external services, timeouts, or rate limiting, and they often resolve themselves after a brief period. Possible Reasons for Transient Failures Resource overloaded:   For example, in high-traffic scenarios, limited system resources (like memory or CPU) can lead to failures when trying to access those resources. Network Issues :  Temporary issues like DNS resolution errors, dropped connections, or network congestion can cause operations to fail. Service Unavailability :  External services or databases might be down or unavailable temporarily.  For example, a database connec...