xlsxPackage.js

import XLSX from 'xlsx'
// String to ArrayBuffer
const s2ab = function (s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i=0; i! =s.length; ++i) view[i] = s.charCodeAt(i) &0xFF;
    return buf;
}
// Export excel related functions
const sheet2blob = function (sheet, sheetName = 'sheet1') {// Convert the file to binary
    var workbook = {
        SheetNames: [sheetName],
        Sheets: {}}; workbook.Sheets[sheetName] = sheet;// Generate excel configuration items
    var wopts = {
        bookType: 'xlsx'.// The type of file to generate
        bookSST: false.// Whether to generate Shared String tables, the official interpretation is that the generation speed slows down, but there is better compatibility on earlier versions of IOS devices
        type: 'binary'
    };
    var wbout = XLSX.write(workbook, wopts);
    var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
    
    return blob;
}
const openDownloadXLSXDialog = function (url, saveName){// Download the template file
    if(typeof url == 'object' && url instanceof Blob){
        url = URL.createObjectURL(url); // Create a blob address
    }
    
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ' '; // HTML5 new attribute to specify the file name to save, can not be suffix, note, file:/// mode does not take effect
    var event;
    if(window.MouseEvent) event = new MouseEvent('click');
    else{
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click'.true.false.window.0.0.0.0.0.false.false.false.false.0.null);
    }
    aLink.dispatchEvent(event);
}

export default {
    XLSX,
    sheet2blob,
    openDownloadXLSXDialog
}
Copy the code

use

import xlxsPackage from 'utils/xlxsPackage.js'

handleDownloadXLXSTemplate () {
    const array = [['the problem'.'answer']]
    const sheet = xlsxPackage.XLSX.utils.aoa_to_sheet(array)
    const blob = xlsxPackage.sheet2blob(sheet)
    xlsxPackage.openDownloadXLSXDialog(blob, 'XXX.xlsx');
}
Copy the code

This article refers to js to generate XLSX/XLS format files and download them to the local