前端 js导出excel

一、导出效果 

二、导出代码 

download() {
  let data = [{
      name: 'aaaa',
      age: 10,
      address: '广东',
      phone: '1',
      wechart: '1'
    },
    {
      name: 'bbbb',
      age: 11,
      address: '广西',
      phone: '2',
      wechart: '2'
    },
    {
      name: 'cccc',
      age: 12,
      address: '山东',
      phone: '3',
      wechart: '3'
    }
  ]
  if (!data.length) {
    this.$Message.warning('没有可以导出的数据');
    return;
  }
  let table = `<table border="1px" cellspacing="0" cellpadding="0">
      <thead>
        <th>序号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>地址</th>
        <th>手机号</th>
        <th>微信号</th>
    </thead>
    <tbody>
    `;

  for (let i = 0; i < data.length; i++) {
    let {
      name,
      age,
      address,
      phone,
      wechart
    } = data[i];
    table += `<tr>
                <td>${i + 1}</td>
                <td>${name} </td>
                <td>${age}</td>
                <td>${address}</td>
                <td>${phone}</td>
                <td>${wechart}</td>
              </tr>`;
  }
  table += '</tbody>';
  table += '</table>';
  let html = `<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
                <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
                <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
                <head>
                </head>
                <body>
                    ${table}
                </body>
              </html>`;
  let url = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
  let a = document.createElement('a');
  a.href = url;
  a.download = `${new Date().Format('yyyyMMddhhmmss')}.xls`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值