Introduction
- We have created Blazor 3.2 WASM with Add/Edit/Delete capabilities and .NET Core in previous articles.
- In this article, we will be adding export capabilities on the home screen with the ability to download Employee data in excel format on the Home screen on the click of a button.
Prerequisites
Refer to my previous article on creating fully functional Blazor WASM with Add/Edit/Delete capabilities.
Output
On a click of Export Button Employee, details are exported in .xlsx Format.
Implementation
Step 1 - Download and set up Gembox NuGet package
Navigate to Tools-->Nuget Package manager and download the latest version of the Gembox spreadsheet and install it in our .NET Core server project.
Import Gembox library in startup.cs with the below statement
- using GemBox.Spreadsheet;
Initialize the Spreadsheet info class and set License Key information.
This needs to be done in startup.cs of Server project in Configure service method
- public void ConfigureServices(IServiceCollection services) {
- services.AddDbContext < AppDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
- services.AddControllersWithViews();
- services.AddRazorPages();
- services.AddScoped < IEmployeeRepository, EmployeeRepository > ();
- SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
- }
This completes the set up for Gembox
Step 2 - Creating .NET Core API for excel Export
Import Gembox library using below syntax
- using GemBox.Spreadsheet;
Create a new Route in Employee Controller.
- [Route("Export")]
- [HttpGet]
- public IActionResult Export() {
- var book = new ExcelFile();
- var sheet = book.Worksheets.Add("Employee");
- IList < Employee > data = _employeeRepository.GetAllEmployees().ToList();
- CellStyle style = sheet.Rows[0].Style;
- style.Font.Weight = ExcelFont.BoldWeight;
- style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
- sheet.Columns[0].Style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
- sheet.Columns[0].SetWidth(150, LengthUnit.Pixel);
- sheet.Columns[1].SetWidth(150, LengthUnit.Pixel);
- sheet.Columns[2].SetWidth(150, LengthUnit.Pixel);
- sheet.Columns[3].SetWidth(150, LengthUnit.Pixel);
- sheet.Columns[5].SetWidth(150, LengthUnit.Pixel);
- sheet.Columns[6].SetWidth(300, LengthUnit.Pixel);
- sheet.Cells["A1"].Value = "EmployeeId";
- sheet.Cells["B1"].Value = "First Name";
- sheet.Cells["C1"].Value = "Last Name";
- sheet.Cells["D1"].Value = "EmailId";
- sheet.Cells["E1"].Value = "City";
- sheet.Cells["F1"].Value = "Comment";
- for (int r = 1; r <= data.Count; r++) {
- Employee item = data[r - 1];
- sheet.Cells[r, 0].Value = item.EmployeeId;
- sheet.Cells[r, 1].Value = item.FirstName;
- sheet.Cells[r, 2].Value = item.LastName;
- sheet.Cells[r, 3].Value = item.Email;
- sheet.Cells[r, 4].Value = item.City;
- sheet.Cells[r, 5].Value = item.Comment;
- }
- SaveOptions options = GetSaveOptions("XLSX");
- using(var stream = new MemoryStream()) {
- book.Save(stream, options);
- return File(stream.ToArray(), options.ContentType, "EmployeeData." + "XLSX");
- }
- }
- private static SaveOptions GetSaveOptions(string format) {
- switch (format.ToUpper()) {
- case "XLSX":
- return SaveOptions.XlsxDefault;
- case "XLS":
- return SaveOptions.XlsDefault;
- case "ODS":
- return SaveOptions.OdsDefault;
- case "CSV":
- return SaveOptions.CsvDefault;
- case "HTML":
- return SaveOptions.HtmlDefault;
- case "PDF":
- return SaveOptions.PdfDefault;
- case "XPS":
- case "PNG":
- case "JPG":
- case "GIF":
- case "TIF":
- case "BMP":
- case "WMP":
- throw new InvalidOperationException("To enable saving to XPS or image format, add 'Microsoft.WindowsDesktop.App' framework reference.");
- default:
- throw new NotSupportedException();
- }
- }
Create a new Excel worksheet object with the name 'Employee'.This is the name of our worksheet which would be downloaded and save on our local machine.
The _employeeRepository.GetAllEmployees() will get a list of all employees of Employee Type.
Here we can call any other repository function and pass data of our choice.
The type of data model needs to be defined in shared library and imported on this page.
Employee Class
- public partial class Employee {
- public int EmployeeId {
- get;
- set;
- }
- [Required]
- [StringLength(50, ErrorMessage = "First name is too long.")]
- public string FirstName {
- get;
- set;
- }
- [Required]
- [StringLength(50, ErrorMessage = "Last name is too long.")]
- public string LastName {
- get;
- set;
- }
- [Required]
- [EmailAddress]
- public string Email {
- get;
- set;
- }
- public string Street {
- get;
- set;
- }
- public string Zip {
- get;
- set;
- }
- public string City {
- get;
- set;
- }
- public string PhoneNumber {
- get;
- set;
- }
- [StringLength(1000, ErrorMessage = "Comment length can't exceed 1000 characters.")]
- public string Comment {
- get;
- set;
- }
- }
We would be exporting 6 properties of Employee class to excel.
We would need to define column formatting and labels for these properties.
GetSaveOptions method accepts a file type. We have created this method with multiple file types. This article is restricted to use of XLSX export.
The file is outputted as a memory stream and can be downloaded and saved on our local machine.
We can also specify the workbook name over here
- using (var stream = new MemoryStream())
- {
- book.Save(stream, options);
- return File(stream.ToArray(), options.ContentType, "EmployeeData."+ "XLSX");
- }
EmployeeData is the sheet name.
The .NET Core API is now ready to be consumed in the Blazor Client app.
Step 3 - Calling .NET Core on Export Export Click and Download File
Add a new Export button on Employeepage.Razor
- <a href="@($"api/employee/export")" class="btn btn-primary-details table-btn">
- <i class="fas fa-info-circle"></i>
- Export
- </a>
On click of Export button, the Export API will be called and the Employee excel file would be downloaded with the name EmployeeData
Gembox provides a lot of capabilities for excel formatting which can be used as per our requirement.
Summary
Through this article, we have learned how to export data in excel format in Blazor WASM using the Gembox spreadsheet library.
Thanks a lot for reading. I hope you liked this article. Please share your valuable suggestions and feedback. Write in the comment box in case you have any questions. Have a good day!