导出Excel .xls格式

1、Excel.js

export function createXlsFile (jsonData) {
let table = '<table>'
// 生成表头
let row = '<tr>'
for (let i = 0; i < jsonData.th.length; i++) {
row += '<th>' + jsonData.th[i] + '</th>'
}
table += row + '</tr>'
let tds = jsonData.tds
for (let i = 0, len = tds.length; i < len; i++) {
let td = '<tr>'
for (let j = 0, jLen = tds[i].length; j < jLen; j++) {
td += '<td>' + tds[i][j] + '</td>'
}
td += '</tr>'
table += td
}
let excelFile = "<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'>"
excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'
excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel'
excelFile += '; charset=UTF-8">'
excelFile += '<head>'
excelFile += '<!--[if gte mso 9]>'
excelFile += '<xml>'
excelFile += '<x:ExcelWorkbook>'
excelFile += '<x:ExcelWorksheets>'
excelFile += '<x:ExcelWorksheet>'
excelFile += '<x:Name>'
excelFile += 'sheet'
excelFile += '</x:Name>'
excelFile += '<x:WorksheetOptions>'
excelFile += '<x:DisplayGridlines/>'
excelFile += '</x:WorksheetOptions>'
excelFile += '</x:ExcelWorksheet>'
excelFile += '</x:ExcelWorksheets>'
excelFile += '</x:ExcelWorkbook>'
excelFile += '</xml>'
excelFile += '<![endif]-->'
excelFile += '</head>'
excelFile += '<body>'
excelFile += table
excelFile += '</body>'
excelFile += '</html>'
let uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8,base64,' + encodeURIComponent(excelFile)
let link = document.createElement('a')
link.href = uri
link.style = 'visibility:hidden'
link.download = jsonData.fileName + '.xls'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}

2、vue 组件引入使用

import { createXlsFile } from '../../utils/Excel'
// 导出
download () {
// console.log(this.newTable)
let filterVal = ['alarmtype', 'passtime', 'name', 'phone', 'sfzh', 'location', 'ishandle', 'isfeedback']
let data = this.formatJson(filterVal, this.newTable)
// console.log(data)
createXlsFile({
fileName: '所有报警',
th: ['报警类型', '报警时间', '联系人', '联系电话', '身份证', '地址', '状态', '反馈'], // 表头
tds: data
})
},
formatJson (filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => {
if (j === 'alarmtype') {
return this.alarmTypeValue(v)
} else if (j === 'ishandle') {
if (v[j] === 1) {
return '已处理'
} else {
return '未处理'
}
} else if (j === 'isfeedback') {
if (v[j] === 1) {
return '已反馈'
} else {
return '未反馈'
}
} else {
return v[j]
}
}))
},

 

posted @ 2021-01-06 14:40  sosolucky  阅读(244)  评论(0编辑  收藏  举报