前端js导出excel方法分享

16231次浏览

前言

之前写个js导出excel的方法,但是发现已经过时了,最近用了一下新的导出方式,可以用,现在分享一下。vue,react都可以用。原理就是通过table导出excel

方法一:

通过csv的方式导出

exportExcel() { // 前端导出excel
  const types = { 'DYNAMIC': '动态创意', 'STATIC': '静态创意', 'VIDEO': '视频创意', 'MATERIAL': '素材创意' }
  let currentGroup = ''
  let exportData = this.showList.map(item => {
    if (item.currentGroup) {
      currentGroup = item.currentGroup
    }
    return {
      creativeId: item.creativeId,
      creativeName: item.creativeName,
      description: item.description&& item.description.replace(/[\n\t\r,]/g,";"),// 把里面的回车和中文逗号换成分号
      creativeSize: `${item.creativeWidth}*${item.creativeHeight}`,
      creativeTime: this.getTime(item.startDate) + ' - ' + this.getTime(item.endDate),
      creativesourceTyle: this.showType(item.creativeSource),
      creativeTypename: types[item.creativeType]
    }
  })
  // console.log(exportData)
  let str = '创意ID,创意名称,创意描述,创意尺寸,创意时间,创意来源,创意类型\n'
  for (let i = 0; i < exportData.length; i++) {
    for (let item in exportData[i]) {
      str += `${exportData[i][item] + '\t'},`
    }
    str += '\n'
  }
  // encodeURIComponent解决中文乱码
  let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
  // 通过创建a标签实现
  var link = document.createElement('a')
  link.href = uri
  // 对下载的文件命名
  let nowTime = `${new Date().getFullYear()}${(new Date().getMonth() + 1)}${new Date().getDate()}`
  link.download = `${currentGroup}-${nowTime}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
},

注:getTime()和showType()都是转换函数,和主流程不搭噶。showList是数组,就是要导出的字段,可以针对导出的字段做过滤

另外需要注意的是,字段里面不能有中文逗号,换行等,可以用replace去除掉

方法二:

base64(s) { return window.btoa(unescape(encodeURIComponent(s))) },
exportExcel() { // 前端导出excel
  console.log(this.showList)
  let str = '<tr><td>代理名称</td><td>allianceid</td><td>attachmentFileId</td>'
  for (let i = 0; i < this.showList.length; i++) {
    str += '<tr>'
    for (let item in this.showList[i]) {
      // 增加\t为了不让表格显示科学计数法或者其他格式
      str += `<td>${this.showList[i][item] + '\t'}</td>`
    }
    str += '</tr>'
  }
  let worksheet = 'Sheet1'
  let uri = 'data:application/vnd.ms-excel;base64,'
  // 下载的表格模板数据
  let template = `<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">
  <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
    <x:Name>${worksheet}</x:Name>
    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
    </head><body><table>${str}</table></body></html>`
  // 下载模板
  window.location.href = uri + this.base64(template)
},//showList是table数据

以上是我最近用过的2中前端导出excel的方法。

xlsx 库

<script
  type="text/javascript"
  src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.1/xlsx.full.min.js"
></script>
<script>
  function ExportData()
  {
          filename='reports.xlsx';
     data=[{Market: "IN", New Arrivals: "6", Upcoming Appointments: "2", Pending - 1st Attempt: "4"},
          {Market: "KS/MO", New Arrivals: "4", Upcoming Appointments: "4", Pending - 1st Attempt: "2"},
          {Market: "KS/MO", New Arrivals: "4", Upcoming Appointments: "4", Pending - 1st Attempt: "2"},
          {Market: "KS/MO", New Arrivals: "4", Upcoming Appointments: "4", Pending - 1st Attempt: "2"}]
      var ws = XLSX.utils.json_to_sheet(data);
      var wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "People");
      XLSX.writeFile(wb,filename);
   }
</script>

npm实现

import { read, utils, writeFile } from 'xlsx';

const handleExport = () => {
  const data = [
    ['orderId', 'orderName', 'orderPrice', 'orderCount', 'orderTotalPrice', 'orderStatus'],
  ];

  orders.forEach((order) => {
    data.push([
      order.orderId,
      order.orderName,
      order.orderPrice,
      order.orderCount,
      order.orderTotalPrice,
      order.orderStatus,
    ]);
    ]);
  });

  const fileName = 'output.xlsx';
  const ws = utils.json_to_sheet(data);
  const wb = utils.book_new();
  utils.book_append_sheet(wb, ws, 'output');
  writeFile(wb, fileName);
}

Tags: jsexcel

相关文章:

  1. 123
    1
    你页面挂了, 大佬
  2. 123
    2
    样式错误 ,丑的飞起
  3. 1234444
    3
    说实话,第一种方法导出的是cvs格式,无法导出xlsx等格式,第二种方法必须要联网才行,如果实在内网上的项目就行不通