word、Excel、PDF预览(Vue项⽬)
Vue项⽬要在内⽹环境进⾏预览,pdf可以直接使⽤浏览器⾃带的⽅式进⾏预览,但是word和excel需要借助插件,预览本地⽂件,或者是内⽹⽂件,可以使⽤以下⽅法进⾏预览:
PDF:vue-pdf
Word: mammoth.js
Excel: SheetJS
1.word预览–mammoth.js
命令:npm install --save mammoth (只能预览.docx⽂件)
-------------word.vue-----------
<template>
<div>
<div id="wordView" v-html="vHtml" />
</div>
</template>
<script>
import mammoth from "mammoth";
export default {
name: "word",
data() {
return {
vHtml: "",
wordURL:''//⽂件地址
};
},
created() {
let vm=this;
vm.wordURL = this.$route.query.wordURL;
const xhr = new XMLHttpRequest();
excel最强教科书完全版pdfxhr.open("get", this.wordURL, true);
if (xhr.status == 200) {
mammoth
.convertToHtml({ arrayBuffer: new sponse) })
.
then(function (resultObject) {
vm.$nextTick(() => {
// document.querySelector("#wordView").innerHTML =
//  resultObject.value;
vm.vHtml=resultObject.value;
});
});
}
};
xhr.send();
},
methods: {
},
};
</script>
<style>
</style>
命令:npm install --save xlsx
---------------excel.vue--------------
<template>
<div id="table">
<el-table :data="tableData" >
<el-table-column
v-for="(value,key,index) in tableData[2]"
:key="index"
:prop="key"
:label="key"
></el-table-column>
</el-table>
</div>
</template>
<script>
import XLSX from "xlsx";
export default {
data() {
return {
tableData: [],
workbook: {},
excelURL: "",
};
},
mounted() {
},
methods: {
readWorkbookFromRemoteFile: function (url) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
let _this = this;
if (xhr.status === 200) {
var data = new sponse);
var workbook = ad(data, { type: "array" });
console.log(workbook);
var sheetNames = workbook.SheetNames; // ⼯作表名称集合          _this.workbook = workbook;
_Table(sheetNames[0]);
}
};
xhr.send();
},
getTable(sheetName) {
console.log(sheetName);
var worksheet = this.workbook.Sheets[sheetName];
this.tableData = XLSX.utils.sheet_to_json(worksheet);
console.log(this.tableData);
},
},
};
</script>
<style lang="stylus" scoped>
#table {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
color: #2c3e50;
margin-top: 60px;
border: 1px solid #ebebeb;
padding: 20px;
width: 80%;
margin: 20px auto;
border-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6), 0 2px 4px 0 rgba(232, 237, 250, 0.5);  border-radius: 10px;
overflow: scroll;
height: 100%;
.tab {
margin: 0 0 20px 0;
display: flex;
flex-direction: row;
}
}
</style>
<style scoped>
.is-active {
background-color: #409eff;
}
span {
background-color: red;
}
</style>
3.pdf预览——vue-pdf
命令:npm install --save vue-pdf
---------------pdf.vue------------------
<template>
<div>
<pdf ref="pdf" :src="pdfUrl" />
</div>
</template>
<script>
import pdf from 'vue-pdf'
export default {
data(){
return: {
pdfUrl: '',
}
}
created() {
const path = 'test.pdf'// 你获取到的pdf路径
// ateLoadingTask解决⽂件件跨域问题
this.pdfUrl = ateLoadingTask(path)
},
}
</script>