In this article you will see how to convert a CSV file to Excel file on server side ASP.NET application and download it from client side angular application
To convert the CSV file, you will use EPPlus package
- Open Visual Studio
- Create a new project using ASP.NET Core with Angular
- Add
Weather.csvinsidewwwrootfolder (refer code sample) - Install nuget package
EPPlus - Open
Controllers\WeatherForecastController.cs - Import
using OfficeOpenXml; - Inject
IWebHostEnvironment envin the constructor - Add the following code to convert csv file to excel and return the file in the response
[HttpGet("Download")]
public IActionResult Download()
{
string csvFilePath = Path.Combine(env.WebRootPath, "Weather.csv");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var format = new ExcelTextFormat();
format.Delimiter = ',';
format.TextQualifier = '"';
using var stream = new MemoryStream();
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Data");
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFilePath), format, OfficeOpenXml.Table.TableStyles.Medium27, FirstRowIsHeader: true);
package.Save();
}
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
- In
ClientApp\src\app\fetch-data\fetch-data.component.htmladd a button to download the excel file
<button type="button" (click)="downloadExcelFromCSV()">Download Excel From CSV</button>
- In
ClientApp\src\app\fetch-data\fetch-data.component.tsadd the method to download the file from the ASP.Net API. - Set the
responseTypetoblobin the httpHeader of angular http call. - Also set the
MIME-Typewhen creatingBlobfrom the response.application/octet-streamorapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
downloadExcelFromCSV() {
this.http.get(this.baseUrl + 'weatherforecast/download', { responseType: 'blob' }).subscribe(data => {
// Filename autogenerated
//const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
//const url = window.URL.createObjectURL(blob);
//window.open(url);
// For Fixed Filename
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = "data.xlsx";
link.click();
})
}
Try Sample
Access Code
expeo-in/AspnetAngularCodeSamples: Asp.net Angular Code Samples (github.com)