In today’s digital age, efficient management of employee information is crucial for any organization. In this blog post, we will walk through the process of creating a simple ASP.NET Core API for managing employee details and exporting them to an Excel file.

Required Packages

Before we dive into the code, let’s take a quick look at the packages we’ll be using for this project:

OfficeOpenXml, Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.Tools, Microsoft.EntityFrameworkCore.SqlServer.

Database Configuration

For managing employee data, we’ll use Entity Framework Core. Create an ‘EmployeeContext’ class that inherits from ‘DbContext’ to configure the database connection and define the ‘EmpDetail’ DbSet for the Employee model.

namespace EmpDetails
{
    public class EmployeeContext: DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> options)
        : base(options)
        {
        }
        public DbSet<Employee> EmpDetail { get; set; } = default!;
    }
}

Employee model

Now, let’s define the Employee model, which represents our employee data structure.

public class Employee
    {
        [Key]
        public int EmpId { get; set; }
        public string? EmpName { get; set; }
        public string? Address { get; set;}
        public string? PhNo { get; set; }
        public int Salary { get; set; }
    }

Creating the API Controller

We can now proceed to create the API controller (EmpDetailController) to manage employee details. This controller will have two main actions:

  1. Inserting Employee Details ([HttpPost(“AddEmpDetail”)]):

This action allows you to insert employee details into the database.

2. Exporting Employee Details to Excel ([HttpGet]):

This action exports employee details to an Excel file and returns it as a downloadable file.

Here’s the complete code for the EmpDetailController:

Ensure that you have the ‘OfficeOpenXml‘ library installed for Excel export.

[Route("api/[controller]")]
    [ApiController]
    public class EmpDetailController : ControllerBase
    {
        private readonly EmployeeContext _context;
        public EmpDetailController(EmployeeContext context)
        {
            _context = context;
        }
        [HttpPost("AddEmpDetail")]
        public IActionResult EnterEmpDetail(Employee emp)
        {
            var user = new Employee
            {
                EmpName = emp.EmpName,
                Address = emp.Address,
                PhNo = emp.PhNo,
                Salary= emp.Salary,
            };
            _context.EmpDetail.Add(user);
            _context.SaveChanges();
            return Ok();
        }
        [HttpGet]
        public IActionResult ExportToExcel()
        {
            var employees = _context.EmpDetail;
            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Employee Details");
               
                worksheet.Cells.LoadFromCollection(employees, true);
                var totalSalaryCell = employees.Count() + 3;
                var totalSalaryColumn = 5;
                var totalSalaryFormula = $"SUM(E2:E{totalSalaryCell - 1})";
                worksheet.Cells[totalSalaryCell, 4].Value = "Total";
                worksheet.Cells[totalSalaryCell, totalSalaryColumn].Formula = totalSalaryFormula;
                using (var headerRange = worksheet.Cells[1,1,1,5])
                {
                    headerRange.Style.Font.Bold = true;
                    headerRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    headerRange.Style.Fill.BackgroundColor.SetColor(Color.YellowGreen);
                }
                var content = package.GetAsByteArray();
                var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                var fileName = "EmployeeDetails.xlsx";
                return File(content, contentType, fileName);
            }
        }
    }
}

[HttpPost(“AddEmpDetail”)]

[HttpGet]

Finally, it converts the Excel package into a byte array, sets the content type to Excel, and returns the Excel file as a response with the filename ‘EmployeeDetails.xlsx’.

To download the file, click the “Download File” button. The Excel file will be downloaded with the data.

Inserting Employee Details:

To add a new employee record, send a POST request to EmpDetail/AddEmpDetail with the employee details in the request body.

Export to Excel:

To export employee details to an Excel file, make a GET request to /api/EmpDetail/ExportToExcel. This will generate an Excel file containing the employee details, along with a total salary calculation.

Conclusion

In conclusion, we have demonstrated how to create a simple ASP.NET Core API for managing employee details and exporting them to Excel.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.