前言
vue项目用
@vue-office/word、@vue-office/excel、@vue-office/pdf比较方便,但是无奈 h5 支持不太友好,所以就选择了用xlsx这个包。h5端预览excel文件,由于项目没有文件服务器,所以只能接口请求文件流进而前端渲染。
代码环境
vant: ^4.8.7
vue: 3.2.45
xlsx: ^0.18.5
引用 xlsx npm包
import { read, utils } from 'xlsx'
请求并处理后端数据流
const xlsxData = ref([])
...
const res = await request(fileId)
// 读取 file 或 blob 对象
const reader = new FileReader()
reader.onload = (e) => {
const data = e.target.result
const arrBuffer = new Uint8Array(data)
const workbook = read(arrBuffer, { type: 'array' })
// 读取 sheet 页名称数组,并设置每个 sheet 页的名字及相对应的内用
workbook.SheetNames.forEach((sheetName: any, index: number) => {
const names = Object.keys(workbook.Sheets[sheetName])
if (names?.length > 1) {
xlsxData.value.push({
// sheet 页名字
name: sheetName,
// sheet 内容
value: utils.sheet_to_html(workbook.Sheets[sheetName])
})
} else {
xlsxData.value.push({
name: sheetName,
value: '暂无内容'
})
}
})
}
reader.readAsArrayBuffer(res.data)
...
template
<van-tabs>
<van-tab v-for="(item) in xlsxData" :key="item.name" :title="item.name">
<div v-html="item.value"></div>
</van-tab>
</van-tabs>
在线预览服务器文件(后端返回服务器文件地址url)
方案一:微软(加载较慢)
let url= "http://xxxx.aaa.com"
let encodeUrl= encodeURIComponent(url)
// https://view.officeapps.live.com/op/view.aspx?src=你的地址(必须全路径,例:http://xxxx.aaa.com)
let previewUrl = 'http://view.officeapps.live.com/op/view.aspx?src='+ encodeUrl
window.open(previewUrl,'_target')
方案二:xdoc(收费)
let url= "http://xxxx.aaa.com"
let encodeUrl= encodeURIComponent(url)
// http://view.xdocin.com/xdoc?_xdoc=你的地址(必须全路径,例:http://xxxx.aaa.com)
let previewUrl = 'http://view.xdocin.com/xdoc?_xdoc='+ encodeUrl
window.open(previewUrl,'_target')