csv-builder-downloader
A dependancy free JavaScript tool for composing and downloading csv files. Written in TypeScript.
Simple Usage
This is will sanitize the values and download a file: csv-download-<timestamp>.csv
const yourData = [[...headers][...row1][...row2]];
new CsvBuilder().addRows(yourData).download();
Advanced Usage
Pass in configuration and make usage match your data model more closely.
const {
defaultFileHeading,
yesterdayFileHeaders,
yesterdayData,
todayFileHeaders,
todayData,
getFileName,
} from yourReducerOrDataModel;
const csvBuilder = new CsvBuilder({
filename: getFileName(),
includeTimeStamp: false,
sanitizeRegex: /[^a-zA-Z0-9:\./_\-@$ ]/g,
nonValueIndices: [0,5]
});
csvBuilder
.addRow(`${defaultFileHeading} Yesterday:`)
.addRow(yesterdayFileHeaders)
.addRows(yesterdayData)
.addNewLine(2);
yesterdayData.forEach((metric) => csvBuilder.addCell(someCalculation(metric)));
csvBuilder.addSection({
title: `${defaultFileHeading} Today:`,
headers: todayFileHeaders,
rows: todayData
});
csvBuilder.changeRegEx(/[^a-zA-Z:\./_\-@$ ]/g);
todayData.forEach((metric) => csvBuilder.addCell(someCalculation(metric)));
csvBuilder.download();
CsvBuilder
Configuration
Option | Default | Type |
---|
encodingType | data:text/csv;charset=utf-8 | String |
file | '' | String |
fileSuffix | .csv | String |
filename | csv-download | String |
includeTimeStamp | true | Boolean |
nonValueIndices | [] | Array |
sanitizeRegex | /[^a-zA-Z0-9:\./_\-@$ ]/g | RegExp |
sanitizeValues | true | Boolean |
Methods
.addCell(val: CELL_TYPE, sanitize: boolean = true)
.addRow(val: CELL_TYPE | ROW_ARRAY_TYPE, sanitize?: boolean)
.addRows(rows: ROW_ARRAY_TYPE[])
.addNewLine(count: number = 1)
.addSection({ title, headers, rows, newLines }: SECTION_TYPE)
.getEncodedFile()
.getFilename()
.changeRegex(passedRegex: RegExp)
.download()
CsvDownloader
If using the CsvBuilder, you do not need to separately use the CsvDownloader, but it can be used on its own if needed.
Configuration (all required if using separately)
Option | Type |
---|
encodedFile | String |
filename | String |
Methods
.getBlob()
.getBlobUrl(csvData: Blob)
.download()