将 json 数据导出为 Excle 表格方式

var datas = [{
    json数据!
}]
/**
 * 导出 json 数据为 Excle 表格
 * @param {json} data 要导出的 json 数据
 * @param {String} head 表头, 可选 参数示例:'名字,邮箱,电话'
 * @param {*} name 导出的文件名, 可选
 */
function jsonToExcel(data, head, name) {
    let str = head ? head + '\n' : '';
    data.forEach(item => {
        // 拼接json数据, 增加 \t 为了不让表格显示科学计数法或者其他格式
        for(let key in item) {
            str = `${str + item[key] + '\t'},`
        }
        str += '\n'
    });
    // console.log(str)
    // encodeURIComponent解决中文乱码
    const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    // 通过创建a标签实现
    const link = document.createElement("a");
    link.href = uri;
    // 对下载的文件命名
    link.download =  `${name + '.csv'}`;
    link.click();
}
/**
 * @param {json} datas 要导出的 json 数据
 * @param {String} head/keys 表头, 可选 参数示例:'名字,邮箱,电话'   /  [名字,邮箱,电话]
 * @param {*} name 导出的文件名, 可选
 */
jsonToExcel(datas,keys, action +"-"+getFullYear+"-"+getMonth +"-"+ getDate +"-"+actiontext  )

猜你喜欢

转载自blog.csdn.net/weixin_52208686/article/details/128798960
今日推荐