js将json数组导出为excel

方式一:
1、定义函数

const jsonData = [
    {
        name:'路人甲',
        phone:'123456789',
        email:'000@123456.com'
    },
    {
        name:'炮灰乙',
        phone:'123456789',
        email:'000@123456.com'
    },
    {
        name:'土匪丙',
        phone:'123456789',
        email:'000@123456.com'
    },
    {
        name:'流氓丁',
        phone:'123456789',
        email:'000@123456.com'
    },
];

/**
 * 导出 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();
}

2、调用

jsonToExcel(jsonData, "姓名,电话,邮箱")

方式二
1、定义函数

function exportJsonToExcel(column, headData, bodyData, sheetName = 'Excle表格') {
    // 组装表头
    let theadHtml = '';
    headData.map(list => {
        let th = ''
        list.map(item => {
            th += `
          <th colspan="${item.colspan || 1}" rowspan="${item.rowspan || 1}">
            ${item.text + '\t'}
          </th>
        `;
        });
        theadHtml += `<tr>${th}</tr>`
    });

    // 组装表体
    let tbodyHtml = ''
    bodyData.map(item => {
        let td = ''
        column.map(n => {
            const val = item[n.key] || ''
            td += `<td style="text-align: center;mso-number-format:'\@';">${val + '\t'}</td>`
        });
        tbodyHtml += `<tr>${td}</tr>`
    });

    // 将table添加到html中,在html中加入excel和sheet元素
    let template = `
      <html lang="" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">
        <head>
          <title></title>
          <xml>
            <x:ExcelWorkbook>
              <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                <x:Name>${sheetName}</x:Name>
                <x:WorksheetOptions>
                  <x:DisplayGridlines/>
                </x:WorksheetOptions>
                </x:ExcelWorksheet>
              </x:ExcelWorksheets>
            </x:ExcelWorkbook>
          </xml>
        </head>
        <body>
          <table>
            <thead>${theadHtml}</thead>
            <tbody>${tbodyHtml}</tbody>
          </table>
        </body>
      </html>
    `;

    // encodeURIComponent 解决中文乱码
    const uri = 'data:text/xlsx;charset=utf-8,\ufeff' + encodeURIComponent(template);

    // 通过创建a标签实现
    const link = document.createElement("a");
    link.href = uri;
    link.download = `${sheetName + '.xlsx'}`; // 设置文件名
    link.click();
}

2、调用函数

// 列
let column = [
  { text: '姓名', key: 'name' },
  { text: '身份证', key: 'personId' },
  { text: '手机号', key: 'phone' },
];

// 表头
let headData = [
  [{ text: '幼儿园一年级', colspan: 3 }],
  [
    { text: '姓名', key: 'name' },
    { text: '身份证', key: 'personId' },
    { text: '手机号', key: 'phone' },
  ]
];

// 表体
let bodyData = [
  {
    name: '张三',
    personId: '12345601',
    phone: '15211112222',
  },
  {
    name: '李四',
    personId: '12345602',
    phone: '15211112222',
  },
  {
    name: '王五',
    personId: '12345603',
    phone: '15211112222',
  },
]

jsonToExcel(column, headData, bodyData, '幼儿园一年级')
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员阿明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值