Angular and JavaScript: export your data to CSV using Typescript

Updated:

Npm: https://www.npmjs.com/package/@molteni/export-csv

GitHub: https://github.com/marco76/export-csv

Goal: easily export arrays and JSON data from your Angular or JavaScript application to Excel / CSV

Very often in our professional web application we visualise information from a database in tables. A common requirement is to export this data to an excel file.

Usually this requires to generate the file on the backend (Java etc.) and send it to the client.

If all the data is already present on the client we can simply use a Typescript function.

Install the npm package

npm i @molteni/export-csv --save 

In your application you can import the package with the following declaration:

import ExportToCSV from "@molteni/export-csv"; 

and call the export for only some columns e.g.:

var exporter = new ExportToCSV(); 
exporter.exportColumnsToCSV(this.blogArticles, "filename", ["title", "link"]); 

or for all the columns, e.g.:

var exporter = new ExportToCSV(); 
exporter.exportColumnsToCSV(this.blogArticles, "filename") 

Code snippet with Angular and UTF-8

excel utf-8
exportToCSV = new ExportToCSV(); 
  objectToExport = [{column : 'äàü£™ , ®, ©,'}, {column: 'second row'}]; 
  download() { 
    this.exportToCSV.exportColumnsToCSV(this.objectToExport, 'filename.csv', ['column']); 
  } 

What it can do

Here the content of the definition file with the methods available.

export declare class ExportToCSV { 
    constructor(); 
    exportAllToCSV(JSONListItemsToPublish: any, fileName: string): void; 
    exportColumnsToCSV(JSONListItemsToPublish: any, fileName: string, columns: string[]): void; 
    static downloadFile(filename: string, data: string, format: string): void; 
    static download(filename: string, data: any): void; 
} 

How it works

The method reads the object passed and puts them in an array. The array is stored in a blob in the navigator (msSaveBlob):

let blob = new Blob([data], {type: format}); 
window.navigator.msSaveBlob(blob, filename);` 

To download a temporary link is created and the click on the link simulated:

let elem = window.document.createElement('a'); 
elem.href = window.URL.createObjectURL(blob); 
elem.download = filename; 
document.body.appendChild(elem); 
elem.click(); 

Excel and UTF-8

Excel has issues importing UTF-8 CSV files. You can read more here: StackOverflow.

Our implementation is compatible with Excel and the UTF-8 characters should correctly represented in Excel.


WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland without 'Cloud'.