vue在線預(yù)覽word、excel、pdf、txt、圖片的方法實例
excel文件預(yù)覽
word文件預(yù)覽
pdf文件預(yù)覽
一、查看word
引用mammoth.js
安裝 npm install --save mammoth
引入import mammoth from “mammoth”;
1.頁面
<div id="wordView" v-html="vHtml"/></div>
2.數(shù)據(jù)
data() { return { vHtml: "", wordURL:'' //文件地址,看你對應(yīng)怎末獲取、賦值 }; }, created() { // 具體函數(shù)調(diào)用位置根據(jù)情況而定 this.readExcelFromRemoteFile(this.wordURL); } methods:{ // 在線查看word文件 readExcelFromRemoteFile: function (url) { var vm = this; var xhr = new XMLHttpRequest(); xhr.open("get", url, true); xhr.responseType = "arraybuffer"; xhr.onload = function () { if (xhr.status == 200) { mammoth .convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) }) .then(function (resultObject) { vm.$nextTick(() => { // document.querySelector("#wordView").innerHTML = // resultObject.value; vm.vHtml = resultObject.value; }); }); } }; xhr.send(); }, }
二、查看Excel
引用sheetjs
安裝 npm install --save xlsx
引入import XLSX from “xlsx”;
1.頁面
<!-- excel查看詳情 --> <div id="table" v-if="!isWord"> <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> </div>
2.數(shù)據(jù)
data() { return { excelData: [], workbook: {}, excelURL: "", //文件地址,看你對應(yīng)怎末獲取、賦值 }; }, created() { // 具體函數(shù)調(diào)用位置根據(jù)情況而定 this.readWorkbookFromRemoteFile(this.wordURL); } methods:{ // 在線查看excel文件 readWorkbookFromRemoteFile: function (url) { var xhr = new XMLHttpRequest(); xhr.open("get", url, true); xhr.responseType = "arraybuffer"; let _this = this; xhr.onload = function (e) { if (xhr.status === 200) { var data = new Uint8Array(xhr.response); var workbook = XLSX.read(data, { type: "array" }); console.log("workbook", workbook); var sheetNames = workbook.SheetNames; // 工作表名稱集合 _this.workbook = workbook; _this.getTable(sheetNames[0]); } }; xhr.send(); }, getTable(sheetName) { console.log(sheetName); var worksheet = this.workbook.Sheets[sheetName]; this.excelData = XLSX.utils.sheet_to_json(worksheet); console.log(this.excelData); }, }
寫的項目
1.頁面
<el-dialog title="預(yù)覽" append-to-body :visible.sync="dialog.dialogVisible" > <div :class="[checkClass]" class="check" /> <div v-if="dialog.isPdf" v-loading="iframeLoading" class="pdfClass"> <iframe :src="dialog.src" type="application/x-google-chrome-pdf" /> </div> <!-- <div v-else-if="dialog.isExcel" class="excelClass" v-html="excelHtml" /> --> <div v-else-if="dialog.isExcel"> <el-table :data="excelData" border stripe :header-cell-style="{'background':'#F5F4F7'}" > <el-table-column type="index" label="序號" width="60" :resizable="false" align="center" /> <el-table-column v-for="(value, key, index) in excelData[0]" :key="index" :prop="key" :label="key" /> </el-table> </div> <div v-else-if="dialog.isWord" class="wordClass" v-html="wordHtml" /> <div v-else class="imgfile"> <img :src="dialog.src" alt="" > </div> </el-dialog>
2.數(shù)據(jù)
<script> import { uploadFile, downloadFileByUniq, downloadFileByFileNames, downloadFileByUniq2 } from '@/base/api/common/' import XLSX from 'xlsx' import mammoth from 'mammoth' export default { data() { return { excelHtml: '', wordHtml: '', excelData: [], dialog: { dialogVisible: false, src: '', isPdf: false, isExcel: false, isWord: false }, } methods: { // 預(yù)覽 previewFn(item) { if (!(item.url.includes('.png') || item.url.includes('.jpg') || item.url.includes('.jpeg') || item.url.includes('.bmp') || item.url.includes('.JPG') || item.url.includes('.PNG') || item.url.includes('.JPEG') || item.url.includes('.BMP') || item.url.includes('.pdf') || item.url.includes('.txt') || item.url.includes('.xls') || item.url.includes('.doc'))) { this.$message.error('文件類型不支持預(yù)覽') return false } if (item.url.includes('.pdf') || item.url.includes('.txt')) { this.dialog.isPdf = true this.dialog.isExcel = false this.dialog.isWord = false this.dialog.src = '' this.iframeLoading = true downloadFileByUniq( encodeURIComponent(item.url) ).then(res => { const blob = new Blob([res], { type: item.url.includes('.pdf') ? 'application/pdf;' : '' }) const href = window.URL.createObjectURL(blob) this.dialog.src = href }).finally(() => { this.iframeLoading = false }) } else if (item.url.includes('.xls')) { this.dialog.isExcel = true this.dialog.isWord = false this.dialog.isPdf = false downloadFileByUniq2( encodeURIComponent(item.url) ).then(data => { const workbook = XLSX.read(new Uint8Array(data), { type: 'array' }) // 解析數(shù)據(jù) var worksheet = workbook.Sheets[workbook.SheetNames[0]] // workbook.SheetNames 下存的是該文件每個工作表名字,這里取出第一個工作表 // this.excelHtml = XLSX.utils.sheet_to_html(worksheet) // 渲染成html const sheet2JSONOpts = { /** Default value for null/undefined values */ defval: ''// 給defval賦值為空的字符串,不然沒值的這列就不顯示 } // 渲染成json this.excelData = XLSX.utils.sheet_to_json(worksheet, sheet2JSONOpts) console.log(this.excelData) }) } else if (item.url.includes('.doc')) { var vm = this this.dialog.isWord = true this.dialog.isExcel = false this.dialog.isPdf = false downloadFileByUniq2( encodeURIComponent(item.url) ).then(data => { mammoth.convertToHtml({ arrayBuffer: new Uint8Array(data) }) .then(function(resultObject) { vm.$nextTick(() => { vm.wordHtml = resultObject.value }) }) }) } else { this.dialog.isPdf = false this.dialog.isExcel = false this.dialog.isWord = false this.dialog.src = item.downloadUrl } this.dialog.dialogVisible = true this.checkClass = 'check' + item.intinvoicestatus },}
補充:vue移動端實現(xiàn)word在線預(yù)覽
word預(yù)覽同樣要使用插件,這里使用的是mammoth插件,首先vue項目引入:
npm install mammoth
在預(yù)覽的頁面導(dǎo)入
import mammoth from ‘mammoth’
同樣的也引用了手勢縮放和移動,在我pdf預(yù)覽那篇文章有說明手勢的操作,使用的AlloyFinger 手勢插件。
html代碼
<template> <div class="excel-container"> <van-nav-bar left-text="返回" title="word查看" left-arrow :fixed="true" :placeholder="true" @click-left="back" /> <div ref="docPreview"></div> </div> </template>
js代碼
同樣的,在本地測試,把word文件放在static文件夾下,然后將url地址換成你static文件夾下的路徑。
<script> import mammoth from 'mammoth' import AlloyFinger from "../../../static/js/alloyfinger.js"; import transform from "../../../static/js/transform.js"; import To from "../../../static/js/to.js"; export default { data () { return { id: '', url:"",// excel文件地址 goPath: '', //將要去的界面 } }, beforeRouteEnter (to, from, next) { //監(jiān)聽從哪個頁面過來 let path = from.fullPath; next(vm => vm.setPath(path)); }, created(){ this.getParams() }, mounted () { this.previewFile(); this.getData(); }, methods: { setPath(path) { this.goPath = path.split("/")[1]; }, //返回鍵 back() { this.$router.push({ name: this.goPath, params: { id: this.id } }) }, getParams() { // 取到路由帶過來的參數(shù) let routerParams = this.$route.params.id // 將數(shù)據(jù)放在當(dāng)前組件的數(shù)據(jù)內(nèi) this.id = routerParams this.url = this.$route.params.url }, previewFile() { let _this=this; try { var xhr = new XMLHttpRequest(); xhr.open("GET", this.url); xhr.responseType = "arraybuffer"; xhr.onload = function(e) { var arrayBuffer = xhr.response; //arrayBuffer mammoth .convertToHtml({ arrayBuffer: arrayBuffer }) .then(displayResult) .done(); function displayResult(result) { _this.$refs.docPreview.innerHTML = result.value || ""; } }; xhr.send(); } catch (e) { console.log(e); _this.$emit("errorPreview"); } }, getData() { let that = this; let element = that.$refs.docPreview; Transform(element); var initScale = 1; this.af = new AlloyFinger(element, { // rotate: function (evt) { //實現(xiàn)旋轉(zhuǎn) // element.rotateZ += evt.angle; // }, multipointStart: function () { initScale = element.scaleX; }, pinch: function (evt) { //實現(xiàn)縮放 element.scaleX = element.scaleY = initScale * evt.zoom; }, pressMove: function (evt) { //實現(xiàn)移動 element.translateX += evt.deltaX; element.translateY += evt.deltaY; evt.preventDefault(); }, }); }, } } </script>
效果
總結(jié)
到此這篇關(guān)于vue在線預(yù)覽word、excel、pdf、txt、圖片的文章就介紹到這了,更多相關(guān)vue在線文件預(yù)覽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue tab切換,解決echartst圖表寬度只有100px的問題
這篇文章主要介紹了vue tab切換,解決echartst圖表寬度只有100px的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07Vue3+vite路由配置優(yōu)化(自動化導(dǎo)入)
這篇文章主要介紹了Vue3+vite路由配置優(yōu)化(自動化導(dǎo)入),需要的朋友可以參考下2023-09-09VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法
這篇文章主要介紹了VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04Vue通過阿里云oss的url連接直接下載文件并修改文件名的方法
這篇文章主要介紹了Vue通過阿里云oss的url連接直接下載文件并修改文件名的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12