downLoadCSV.js 1.3 KB
Newer Older
B
BingBlog 已提交
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
// const JSON_TO_SHEET = XLSX.utils.json_to_sheet;
const aoaToSheet = XLSX.utils.aoa_to_sheet;
const saveAs = FileSaver.saveAs;
function s2ab(s) {
    if (typeof ArrayBuffer !== 'undefined') {
        let buf = new ArrayBuffer(s.length);
        let view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) {
            view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
    }
    let buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) {
        buf[i] = s.charCodeAt(i) & 0xFF;
    }
    return buf;
}

/**
 * download Excel
 *
 * @desc transform data like [['A', 'B', 'C'], ['1', '2', '3'],[['1-1', '2-1', '3-1']]] to xlsx and download
 * @param {Array} data the data for the xlsx
 * @param {string} name filename
 */
export const generateXLSXandAutoDownload = function (data, name) {
    let wopts = {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
    };
    let ws = aoaToSheet(data);
    let wb = {
        SheetNames: ['Export'],
        Sheets: {},
        Props: {}
    };
    wb.Sheets.Export = ws;
    let wbout = XLSX.write(wb, wopts);
    saveAs(
        new Blob(
            [s2ab(wbout)],
            {
                type: 'application/octet-stream'
            }
        ),
        name + '.xlsx' || 'sheetjs.xlsx'
    );
};