js导出csv文件

js导出csv文件

用到了json2csv依赖包,首先安装依赖

npm install json2csv --save
const { Parser } =  require('json2csv');

/**
  * @param {String} fields[表头]
  * @param {String} data[导出的json数据]
  * @param {String} fileName[导出的文件名]
  */
exportCSV(fields,data,fileName){
  const csv = createCVSData(fields,data);
    if(isIE()){
        // IE10以及Edge浏览器
        const BOM = "\uFEFF";
        // 文件转Blob格式
        let csvData = new Blob([BOM + csv], { type: "text/csv" });
        navigator.msSaveBlob(csvData, `${fileName}.csv`);
    }else {
        let downloadLink = document.createElement("a");
        downloadLink.href = getDownloadUrl(cvs);
        downloadLink.download = `${fileName}.csv`; 
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink); 
    }
    return csv;
},
const createCSVData  = function(fields,data){
    const json2csvParser  = new Parser({fields}) ;
    const csv = json2csvParser.parse(data)
    return csv;
}
const getDownloadUrl = function(csvData){
    var _utf = "\uFEFF"; // 为了使Excel以utf-8的编码模式,同时也是解决中文乱码的问题
    if (window.Blob && window.URL && window.URL.createObjectURL) {
        var csvData = new Blob([_utf + csvData], {
            type: 'text/csv'
        });
        return URL.createObjectURL(csvData);
    }
}
const isIE = function() {
    let isIE = false;
    if (navigator.userAgent.indexOf("compatible") > -1 &&navigator.userAgent.indexOf("MSIE") > -1) {
        // ie浏览器
        isIE = true;
    }
    if (navigator.userAgent.indexOf("Trident") > -1) {
        // edge 浏览器
        isIE = true;
    }
    return isIE;
}

调用:


//fields 要与json的key名相对应
const fields = ['id','date','channal','addDeviced'];
exportCSV(fields,jsonData,'文件名');

你可能感兴趣的:(javascript)