导出CSV文件,因没有BOM头,而导致 文本打开CSV文件时正常,excel打开是中文乱码。 解决办法是添加BOM头。 前端添加BOM头的示例方法如下:
async exportData() {
let confirm = await this.$confirm(
'默认导出【已归档】和【未归档】的患者数据,也可按照归档状态选择,是否继续?',
'导出提示',
{
type: 'warning'
}
).catch(action => {
return false
})
if (confirm) {
let dateStr = XEUtils.toDateString(new Date(), 'yyyyMMddhhmmss')
let fileName = `data_${dateStr}.csv`
let params = {
orgcode: this.currentUserInfo.orgCodg,
...this.filter
}
const response = await firstPageService.exportData(params)
// 处理文件下载
// const blob = new Blob([response.data], {
// type: 'text/csv;charset=UTF-8'
// })
const BOM = new Uint8Array([0xEF, 0xBB, 0xBF])
const arrayBuffer = await response.data.arrayBuffer()
const combined = new Uint8Array(BOM.length + arrayBuffer.byteLength)
combined.set(BOM, 0)
combined.set(new Uint8Array(arrayBuffer), BOM.length)
const blob = new Blob([combined], {
type: 'text/csv;charset=UTF-8'
})
const downloadUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = downloadUrl
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
// 清理资源
window.URL.revokeObjectURL(downloadUrl)
document.body.removeChild(link)
this.$message({
message: '导出成功',
showClose: true,
type: 'success'
})
}
},
关键部分是:
const BOM = new Uint8Array([0xEF, 0xBB, 0xBF])
const arrayBuffer = await response.data.arrayBuffer()
const combined = new Uint8Array(BOM.length + arrayBuffer.byteLength)
combined.set(BOM, 0)
combined.set(new Uint8Array(arrayBuffer), BOM.length)
const blob = new Blob([combined], {
type: 'text/csv;charset=UTF-8'
})