第一步:安装
//excel文档预览组件
npm install @vue-office/excel
第二步:获取base64编码,存入sessionStorage并通过router.resolve 结合 window.open 打开新窗口(参考文章--参数传递http://t.csdn.cn/jm81E)
let baseContent = res[0].data.Base64Content//获取后端返回的base64编码
//使用sessionStorage,存储base64编码用于文件预览页面,不使用状态机,因为打开了新窗口,组件实例已更新
//这里存储的时候文件太大时,可能会超出session限制,可以使用try catch 捕获错误并提示并阻止打开新窗口,要求用户下载后在本地查看
try {
sessionStorage.setItem('BASE_CONTENT', baseContent)
}
catch (e) {
ElMessage({
message: '文件长度过长,请下载查看!',
type: 'warning',
})
sessionStorage.clear()
return
}
let url = router.resolve({
path: '/file-preview',
})
// 打开新窗口
window.open(url.href)
第三步:准备用于预览文件的页面并渲染
注意:文件预览页面的根节点需要设置为100vh,否则可能会导致excel文件下面留白过多
<template> <div class="test"> <vue-office-excel :src="customBlobContent"> </vue-office-excel> </div> </template> <script lang="ts" setup> //引入VueOfficeExcel组件 import VueOfficeExcel from '@vue-office/excel' //引入相关样式 import '@vue-office/excel/lib/index.css' import { nextTick, onMounted, reactive, ref } from 'vue' let customBlobContent = ref() //base64转换为blob(注意这里的base64为没有前半部分的纯编码) function base64ToBlob(baseContent: string) { let mime = baseContent.match(/:(.*?);/) //获取分割后的base64前缀中的类型 let bstr = window.atob(baseContent) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([u8arr], { type: mime }) } onMounted(() => { // 获取数据 let baseContent = sessionStorage.getItem('BASE64_CONTENT') if (baseContent != null) { // 转blob并渲染 customBlobContent.value = base64ToBlob(baseContent) } }) </script> <style lang="scss" scoped> html, body { width: 100%; height: 100%; } .test{ height: 100vh; } </style>
问题:当用户打开控制台后打开预览页面或者缩小了浏览器后打开预览页面再关闭控制台或者放大浏览器,文件预览页面高度无法保持与浏览器高度一致
解决:通过监听浏览器高度变化,重新刷新一次页面,通过设置的样式为100vh恢复页面高度
01.定义一个用来监听的变量
const screenHeight = ref('')
02.在onMounted生命周期里面通过window.onresize方法获取屏幕高度并赋值给screenHeight,用于监听屏幕高度变化(Window对象是客户端javascript最高层对象之一,只要打开浏览器窗口,不管该窗口中是否有打开的网页,当遇到BODY、FRAMESET或FRAME元素时,都会自动建立window对象的实例。)
onMounted(() => { // 获取数据 let baseContent = sessionStorage.getItem('BASE_CONTENT') if (baseContent != null) { // 转blob并渲染 customBlobContent.value = base64ToBlob(baseContent) } // 通过window.onresize方法获取屏幕高度并赋值给screenHeight,用于监听屏幕高度变化 window.onresize = () => { return (() => { window.screenHeight = document.body.clientHeight screenHeight.value = window.screenHeight })() } })
03.watch监听
watch(screenHeight, val => { //监听到screenHeight的变化就刷新页面 router.go(0) })
参考:vue-office-excel组件源码以及docx、pdf、excel文件预览
参考链接https://github.com/501351981/vue-office
另外:luckysheet似乎也不错,但是只能预览excel,可以试试
参考链接https://gitee.com/mengshukeji/Luckysheet/blob/master/README-zh.md