一、以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导出(不限文件类型)
- 请求接口responseType:’blob’,接口返回二进制流
- IE10提供window.navigator.msSaveBlob和msSaveOrOpenBlob方法可以直接保存到本地,接收参数(new Blob(data),’带后缀文件名’)
-
其他浏览器:
-
生成Blob对象,new Blob(array, options)
-
生成对象URL,指向附件地址,createObjectURL(blob)
-
创建<a>标签,href属性为对象URL,download属性为带后缀文件名,display:none
-
append到body里面,a.click()触发事件,删除节点
-
释放对象URL,revokeObjectURL
-