<button class="btn btn-primary" @click="openPdfViewer(scope)"> 预览</button> 点击按钮,弹个框,框里是文件的容器元素。然后用v-if来控制元素的隐藏与显示以下是结构。
<el-dialog title="预览" :visible.sync="previewDialog" :append-to-body="true" fullscreen center> <iframe v-if="previewType == 1" :src="url" frameborder="0" width="100%" height="800px"></iframe> <!-- excel --> <div v-if="previewType == 2" v-html="excelHtml" ref="execl" class="excel_preview_table"> </div> <!-- word --> <div v-if="previewType == 3" ref="word" style="font-size: 18px;text-align: center;margin-top: 30px;"> </div> </el-dialog> 前端要用到的插件:
execl用到的是import XLSX from 'xlsx'; 可以用npm i xlsx下载,支持xls,xlsx。
word用到的是 const docx = require("docx-preview"); window.JSZip = require("jszip");
可以用npm i docx-preview@0.1.4 (版本可以根据自己的情况,我是直接用的这个) , npm i jszip下载,支持doc,docx。
import XLSX from 'xlsx';//引入const docx = require("docx-preview");window.JSZip = require("jszip"); 在methods定义函数,用axios调后端接口,拿到后端返回的数据,根据文件格式进行对应的处理
// 文件预览 openPdfViewer(scope) { // return // this.fileId = scope.row.id; var formdata = new FormData(); formdata.append('id', scope.row.id); if (scope.row.attachmentName.endsWith('.pdf')) { this.$axios({ url: '/businessTechnology/preview', data: formdata, method: 'post', responseType: 'blob' }).then(res => { // console.log(res.data.type); this.previewDialog = true this.previewType = 1 const blob = new Blob([res.data], { type: 'application/pdf' }); // 创建用于作为PDF预览源的Blob的URL this.url = URL.createObjectURL(blob); }).catch(error => { console.error('Error getting file:', error); }); } else if (scope.row.attachmentName.endsWith('.xls') || scope.row.attachmentName.endsWith('.xlsx')) { console.log('execl'); this.$axios({ method: 'post', data: formdata, responseType: 'arraybuffer', // 设置响应体类型为arraybuffer url: '/businessTechnology/preview', }).then(res => { console.log(res); this.previewDialog = true this.previewType = 2 let workbook = XLSX.read(new Uint8Array(res.data), { type: "array" }); // 解析数据 let worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表 this.excelHtml = XLSX.utils.sheet_to_html(worksheet); // 渲染 console.log(this.excelHtml); }); } else if (scope.row.attachmentName.endsWith('.doc') || scope.row.attachmentName.endsWith('.docx')) { console.log('word'); this.$axios({ method: 'post', data: formdata, responseType: 'blob', url: '/businessTechnology/preview', }).then(res => { this.previewType = 3 this.previewDialog = true this.$nextTick(()=>{ docx.renderAsync(res.data,this.$refs.word) // 渲染到页面预览 }) }); } }, 本人亲测,可以正常使用,有问题可以一起探讨。














