Convert CSV file to Excel and Download from ASP.NET Angular Application


Last Updated: 1/16/2022

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.csv inside wwwroot folder (refer code sample)
  • Install nuget package EPPlus
  • Open Controllers\WeatherForecastController.cs
  • Import using OfficeOpenXml;
  • Inject IWebHostEnvironment env in 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.html add 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.ts add the method to download the file from the ASP.Net API.
  • Set the responseType to blob in the httpHeader of angular http call.
  • Also set the MIME-Type when creating Blob from the response. application/octet-stream or application/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

Expeo Tutorials - ASP.NET Angular Code Samples CSV to Excel (expeoaspnetangularcodesamples.azurewebsites.net)

Access Code

expeo-in/AspnetAngularCodeSamples: Asp.net Angular Code Samples (github.com)

References

MIME-Types