前端导出(JSON\数据流)

一、以excel的格式导出JSON数据

const timestamp2string = (timestamp) => {
  const now = new Date(timestamp)
  const Y = now.getFullYear().toString()
  const M = (now.getMonth() + 1).toString()
  const D = now.getDate().toString().length === 1? '0' + now.getDate() : now.getDate()
  const h = now.getHours().toString()
  const m = now.getMinutes().toString()
  const s = now.getSeconds().toString()
  return {
      Y,
      M,
      D,
      h,
      m,
      s,
      all: Y + M + D + h + m + s,
      str: Y + '年' + M + '月' + D + '日' + ' ' + h + ':' + m + ':' + s
  }
}
// 要导出的数组
const list = [
  {
    exceptionId: '123',
    stationName: '车间1',
    deviceCode: 'D1',
    warnTime: 1664419522806,
    warnEndTime: 1667184327450,
    recorder: '提交人',
    warnDesc: '坏了',
    warnReason: '突然坏了',
    warnCode: 'Code1',
    shortTermTreatment: '等等看',
    longTermTreatment: '卖废品'
  }
]
if (!list.length) {
  console.error('无导出数据')
  return
}
const tableHead = {
    exceptionId: '故障ID',
    stationName: '车间名称',
    deviceCode: '设备编号',
    warnTime: '故障发生时间',
    warnEndTime: '故障结束时间',
    recorder: '提交人',
    warnDesc: '故障描述',
    warnReason: '故障原因',
    warnCode: '故障代码',
    shortTermTreatment: '短期处理方式',
    longTermTreatment: '长期处理方式'
}
let str = ''
/**
 * 每行数据用\n换行
 * 每个单元格用,分隔
 * 表格内容每个单元格最后加\t,避免出现科学计数法等格式
 * 最后用encodeURIComponent防止中文乱码
 */
// 表头
for(let key in list[0]) {
    str += `${tableHead[key]},`
}
str = str.slice(0, -1) + '\n'
// 表格内容
for(let i = 0; i < list.length; i++) {
    for(let key in list[i]) {
        if (key === 'warnTime' || key === 'warnEndTime') {
            str += `${timestamp2string(list[i][key]).str + '\t'},`
        } else {
            str += `${list[i][key] + '\t'},`
        }
    }
    str += '\n'
}
const uri = 'data:text/xlsx;charset=utf-8,\ufeff' + encodeURIComponent(str);
const link = document.createElement("a")
link.href = uri
const now = timestamp2string(Date.now())
link.download =  `故障记录${now.all}.xlsx`
link.click()

二、数据流通过blob导出(不限文件类型)

  1. 请求接口responseType:’blob’,接口返回二进制流
  2. IE10提供window.navigator.msSaveBlob和msSaveOrOpenBlob方法可以直接保存到本地,接收参数(new Blob(data),’带后缀文件名’)
  3. 其他浏览器:

    1. 生成Blob对象,new Blob(array, options)

    2. 生成对象URL,指向附件地址,createObjectURL(blob)

    3. 创建<a>标签,href属性为对象URL,download属性为带后缀文件名,display:none

    4. append到body里面,a.click()触发事件,删除节点

    5. 释放对象URL,revokeObjectURL

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值