Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
87 lines (64 sloc) 3.03 KB
id title date author layout guid permalink image categories tags
985
Angular and JavaScript: export your data to CSV using Typescript
2017-03-05 00:45:29 +0000
Marco Molteni
post
/2017/03/05/angular-and-javascript-export-your-data-to-csv-using-typescript/
/wp-content/uploads/2017/03/excel-100x37.png
Angular
Angular 2
AngularJS
java
javascript
TypeScript
csv
excel
export
TypeScript

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

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

Limitations: This method doesn’t work on Safari.

Online example: http://angular.cafe

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 {
    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();