前端vue解决导出Excel自定义标题头
数据:
[
{
"shipName": "XC4273",
"shipLength": "史洋",
"portName": "电建渔港01",
"phone": "18273414451",
"cmdType": "北斗",
"portTypes": "进港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "N61260",
"shipLength": "姚强",
"portName": "电建渔港01",
"phone": "14602856354",
"cmdType": "雷达",
"portTypes": "出港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "UN8986",
"shipLength": "黄杰",
"portName": "电建渔港02",
"phone": "18344561742",
"cmdType": "雷达",
"portTypes": "进港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "GN6578",
"shipLength": "郭磊",
"portName": "电建渔港01",
"phone": "11184687074",
"cmdType": "北斗",
"portTypes": "出港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "CO5465",
"shipLength": "田强",
"portName": "电建渔港01",
"phone": "19657941539",
"cmdType": "AIS",
"portTypes": "进港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "V45379",
"shipLength": "朱霞",
"portName": "电建渔港03",
"phone": "18417926181",
"cmdType": "北斗",
"portTypes": "出港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "R21063",
"shipLength": "秦军",
"portName": "电建渔港02",
"phone": "12866373803",
"cmdType": "雷达",
"portTypes": "出港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "XR9061",
"shipLength": "吴强",
"portName": "电建渔港01",
"phone": "13814522161",
"cmdType": "雷达",
"portTypes": "进港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "CU6806",
"shipLength": "吕娜",
"portName": "电建渔港01",
"phone": "14705143463",
"cmdType": "北斗",
"portTypes": "进港",
"startTime": "2024-08-08 12:21:00"
},
{
"shipName": "HG5566",
"shipLength": "薛艳",
"portName": "电建渔港04",
"phone": "13480957859",
"cmdType": "北斗",
"portTypes": "出港",
"startTime": "2024-08-08 12:21:00"
}
]
函数调用
exportToExcel(
tableData.value,
{
船名: 'shipName',
船主: 'shipOwner',
渔港名称: 'portName',
联系方式: 'phone',
终端类型: 'cmdType',
进出港类型: 'portTypes',
进出港时间: 'startTime'
},
'船只数据导出.xlsx'
)
函数封装
function exportToExcel(data, headers) {
// 创建一个工作簿
const workbook = XLSX.utils.book_new()
// 转换数据为工作表,使用传入的headers作为列名
const ws = XLSX.utils.json_to_sheet(
data.map((item) => {
const row = {}
for (const header in headers) {
if (headers.hasOwnProperty(header) && item.hasOwnProperty(headers[header])) {
row[header] = item[headers[header]]
}
}
return row
})
)
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(workbook, ws, '船只数据')
// 生成Excel文件
const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })
// 触发下载
function s2ab(s) {
const buf = new ArrayBuffer(s.length)
const view = new Uint8Array(buf)
for (let i = 0; i < s.length; i++) {
view[i] = s.charCodeAt(i) & 0xff
}
return buf
}
const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = '船只数据.xlsx'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}