Skip to content

Instantly share code, notes, and snippets.

@andrisro
Last active March 30, 2020 10:36
Show Gist options
  • Save andrisro/b7700ce5c6cf852bcc57f8f9406724b1 to your computer and use it in GitHub Desktop.
Save andrisro/b7700ce5c6cf852bcc57f8f9406724b1 to your computer and use it in GitHub Desktop.
Angular 8 Typescript Build CSV from JSON
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CsvService {
/*
object in array = line
Execute:
- 1.) buildCsv with any array filled with content objects
- 2.) execute downloadCsv method to download the csv from the browser
*/
public buildCsv(items: Array<any>): string {
let csvContent = 'data:text/csv;charset=utf-8,';
let headerRow = '';
for (let [key, value] of Object.entries(items[0])) {
headerRow += key + ';';
}
if (headerRow.length > 1) {
headerRow = headerRow.substr(0, headerRow.length - 1);
}
csvContent = csvContent + headerRow + '\n';
for (let item of items) {
let row = '';
for (let [key, value] of Object.entries(item)) {
row += value + ';';
}
if (row.length > 1) {
row = row.substr(0, row.length - 1);
}
csvContent = csvContent + row + '\n';
}
return csvContent;
}
public downloadCsv(csvContent: string) {
let encodeUri = encodeURI(csvContent);
let link = document.createElement('a');
link.setAttribute('href', encodeUri);
link.setAttribute('download', 'csvData.csv');
document.body.appendChild(link);
link.click();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment