-
Notifications
You must be signed in to change notification settings - Fork 8
/
csv-exportor.js
35 lines (32 loc) · 880 Bytes
/
csv-exportor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import CSV from 'comma-separated-values';
/**
* generate data url of the generated csv file
* @param {*} data
* @param {*} options
* @returns {String} dataUrl of generated csv file
*/
function genUrl(data, options) {
const encoded = new CSV(data, options).encode();
const dataBlob = new Blob([`\ufeff${encoded}`], { type: 'text/plain;charset=utf-8' });
return window.URL.createObjectURL(dataBlob);
}
/**
* generate csv file from data, and automatically download the file for browser
* @param {*} data
* @param {*} options
* @param {*} fileName
*/
function downloadCsv(data, options, fileName) {
const url = genUrl(data, options);
const a = document.createElement('a');
document.body.appendChild(a);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
export default {
genUrl,
downloadCsv,
};