使用vue框架,在线打开 word、excel、pdf 这三种格式的文件的方式。
vue项目在页面打开 word excelpdf三种格式的文档
背景: 用户要求上传的word、excel、pdf 能够在线预览,要求不是很高,能打开查看一下大致内容就行。
准备工具:Vue、Nginx(没有它或者准备一个可以回传文件的后端接口就行,这个在这里用于代理本地文件)、对应的插件。
1、excel 的网页打开
a.首先 npm 导入 excel 处理的插件 : npm install --save xlsx
b.用了 elementui 的 弹框组件 与 表格组件,来完成内容的展示部分
<el-dialog
class="unit-dialog"
v-if="excelShow"
:visible.sync = 'excelShow'
:title="dialogtitle"
width="1000px"
append-to-body
:close-on-click-modal="false"
top="10vh"
>
<el-table :data="excelData" style="width: 100%">
<el-table-column
v-for="(value, key, index) in excelData[2]"
:key="index"
:prop="key"
:label="key"
></el-table-column>
</el-table>
</el-dialog>
c. 提交请求,获取后端返回的二进制文件流,请注意接口请求的response Type 类型 为 arraybuffer,如代码:
//图片巡检导出
exportDeviceInspect: (params) => {
return axios({
url: `${baseUrl}/XXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXX`,
method: 'post',
data: params,
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json'
}
})
},
然后调用接口,对返回参数进行解析与渲染
var XLSX = require("xlsx");//引入xlsx插件
imageCheckApi.exportDeviceInspect(params).then((res) => {
//excel 在网页打开
this.excelShow = true;
var data = new Uint8Array(res.data);
var excelData = XLSX.read(data, { type: "array" });
var sheetNames = excelData.SheetNames; // 工作表名称集合
var worksheet = excelData.Sheets[sheetNames[0]];
this.excelData = XLSX.utils.sheet_to_json(worksheet);
})
效果图(样式没精修,将就看看):
2、word文档在网页打开
a. 引入docx 插件 npm i docx-preview
b.在上面弹窗的基础上 把表格换成普通的 div标签,然后绑定一个 ref 叫 file
<el-dialog
class="unit-dialog"
v-if="excelShow"
:visible.sync = 'excelShow'
:title="dialogtitle"
width="1000px"
append-to-body
:close-on-click-modal="false"
top="10vh"
>
<div v-html="vHtml" ref="file"></div>
</el-dialog>
c.为了方便看,我把请求写到方法里面了,这里用的是type 是 blob 二进制流,请注意哦!
备注:这里的地址跟 excel 的地址是有区别的,excel是我们后端正常的返回地址,这里用的是我自己定义的地址,用了nginx转发,拿到的是我本地的文档,具体转发有不懂的可以评论找我,这里不讲了,实际效果是一样的。
let docx = require('docx-preview');//引入docx插件
this.$axios({
url: `/Ubuntu.docx`,
method: 'get',
data: params,
responseType: 'blob',
headers: {
'Content-Type': 'application/json'
}
}).then((res) => {
let that = this;
that.excelShow = true;
setTimeout(() => {
this.$nextTick(() => {
//带格式文本
docx.renderAsync(res.data, this.$refs.file);
})
}, 200)
})
d.效果图 (这个插件是带格式的,我觉得挺好的):
3、PDF 在网页的打开
这个更简单了,这个插件就是一个封装好的组件,你只需要传入对应参数就行
a. 导入组件 npm install --save vue-pdf
b. 引入页面
import pdf from 'vue-pdf';
components: { pdf}, // components 记得加上组件哦
然后 页面使用组件
<el-dialog
class="unit-dialog"
v-if="excelShow"
:visible.sync = 'excelShow'
:title="dialogtitle"
width="1000px"
append-to-body
:close-on-click-modal="false"
top="10vh"
>
<pdf src="/pdf.pdf"></pdf>
</el-dialog>
效果(也是带格式的):
这个 pdf 一般加载的时候都是带有页码或者其他的回调方法,有需要的可以研究研究
更多推荐
所有评论(0)