Limitations: This method doesn’t work on Safari.

Online example:

Goal: easily export the table’s 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")

What it can do

Here the content of the definition file:

export declare class ExportToCSV {
    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); = filename;