No.1
install
npm install xlsx docx-preview --save
No.2
create a new component
<template>
<div >
<div v-if="previewData.type == 'doc'" ref="file"></div>
<div v-if="previewData.type == 'xls'" v-html="tableau"></div>
</div>
</template>
<script>
import axios from 'axios'
let docx = require('docx-preview');
const XLSX = require("xlsx")
export default {
name: "index",
props: {
previewData: {
default: {
type: 'doc',
url: ''
}
},
},
data() {
return {
tableau: '',
pdfUrl: ''
}
},
created() {
if(this.previewData.url == '') {
this.msgWarning('文件路径为空')
} else {
switch (this.previewData.type) {
case 'doc':
axios({
method: 'get',
responseType: 'blob', // 设置响应文件格式
url: this.previewData.url,
}).then(({data}) => {
docx.renderAsync(data,this.$refs.file) // 渲染到页面预览
})
break
case 'xls':
axios.get(this.previewData.url,{
responseType: "arraybuffer", // 设置响应体类型为arraybuffer
}).then(({data})=> {
let workbook = XLSX.read(new Uint8Array(data), {type:"array"}); // 解析数据
let worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
this.tableau = XLSX.utils.sheet_to_html(worksheet); // 渲染
})
}
}
},
methods: {
}
}
</script>
<style scoped>
</style>
No.3
import and ues in you page
<Preview :previewData="previewData"></Preview>
import Preview from '@/components/Preview';
components: {
Preview
},
previewData: {
type: 'doc',
url: ''
},