vue在线预览word、excel、pdf、txt、图片的方法实例

目录
  • excel文件预览
  • word文件预览
  • pdf文件预览
  • 一、查看word
    • 引用mammoth.js
  • 二、查看Excel
    • 引用sheetjs
  • 写的项目
    • 1.页面
    • 2.数据
  • 补充:vue移动端实现word在线预览
  • 总结

excel文件预览

word文件预览

pdf文件预览

一、查看word

引用mammoth.js

安装 npm install --save mammoth

引入import mammoth from “mammoth”;

1.页面

<div id="wordView" v-html="vHtml"/></div>

2.数据

data() {
  return {
    vHtml: "",
    wordURL:''  //文件地址,看你对应怎末获取、赋值
  };
},
created() {
  // 具体函数调用位置根据情况而定
  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.数据

data() {
  return {
    excelData: [],
    workbook: {},
    excelURL: "", //文件地址,看你对应怎末获取、赋值
  };
},
created() {
  // 具体函数调用位置根据情况而定
  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="预览"
      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.数据

<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: {
// 预览
    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('文件类型不支持预览')
        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' }) // 解析数据
          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移动端实现word在线预览

word预览同样要使用插件,这里使用的是mammoth插件,首先vue项目引入:

npm install mammoth

在预览的页面导入

import mammoth from ‘mammoth’

同样的也引用了手势缩放和移动,在我pdf预览那篇文章有说明手势的操作,使用的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) { //监听从哪个页面过来
       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() {
       // 取到路由带过来的参数
       let routerParams = this.$route.params.id
       // 将数据放在当前组件的数据内
       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) {  //实现旋转
          //   element.rotateZ += evt.angle;
          // },
          multipointStart: function () {
              initScale = element.scaleX;
          },
          pinch: function (evt) {   //实现缩放
            element.scaleX = element.scaleY = initScale * evt.zoom;
          },
          pressMove: function (evt) {   //实现移动
            element.translateX += evt.deltaX;
            element.translateY += evt.deltaY;
            evt.preventDefault();
          },
        });
      },
    }
  }
</script>

效果

总结

到此这篇关于vue在线预览word、excel、pdf、txt、图片的文章就介绍到这了,更多相关vue在线文件预览内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • vue实现pdf文档在线预览功能

    针对android系统不支持pdf文档在线预览,可通过引入pdf.js插件实现,其具体实现步骤如下 一.引入插件 方式一:npm install --save pdfjs-dist,安装完成后在vue项目的node_modules出现如下依赖 方式二:只引入pdf.js的核心文件pdf.js和pdf.work.js,其他无关的文件全部删除,如图 方式三:将插件直接放在static文件夹下,如图 二.前端页面代码 方式一和方式二:特点精简 <template> <div> <c

  • vue-pdf实现文件在线预览

    本文实例为大家分享了vue-pdf实现文件在线预览的具体代码,供大家参考,具体内容如下 提示:记录一下vue-pdf使用方法,避免忘记,便于后面使用 前言 提示:以下是本篇文章正文内容,下面案例可供参考 一.安装 npm install --save vue-pdf 二.pdf 页面显示 1.html <template> <div class="pdf-box"> //pdf展示 <pdf class="pdf" :page=&quo

  • Vue实现在线预览pdf文件功能(利用pdf.js/iframe/embed)

    前言 最近在做一个精品课程,需要在线预览课件ppt,我们的思路是将ppt转换为pdf在线预览,所以问题就是如何实现在线预览pdf了. 在实现的过程中,为了更好地显示效果,我采用了多种不同的方法,最终选择效果最好的pdf.js. 实现方法: 1:iframe 采取iframe将pdf嵌入网页从而达到预览效果,想法很美好,实现很简单,但显示很残酷- 虽然一行代码简洁明了,打开谷歌浏览器效果也还行,但缺点也是十分明显的!!!! <iframe src="http......" widt

  • vue实现在线预览office文件的示例代码

    最近在做电子档案,后端提供了文件的华为云的oss链接.已经实现了点击下载文件的功能.但是呢,他们又希望常规的文件,可以直接点击预览,不需要下载. 按道理说,做文件的在线预览,买个第三方服务什么的,后端部署一下服务,前端对接一下,就通通搞定. 顶不住第三方基本上是要money的.那不想掏money,还有什么解决方法呢. 方法一 用微软的office online进行在线预览 https://view.officeapps.live.com/op/view.aspx?src=文件地址 例:https

  • vue实现在线预览pdf文件和下载(pdf.js)

    最近做项目遇到在线预览和下载pdf文件,试了多种pdf插件,例如jquery.media.js(ie无法直接浏览) 最后选择了pdf.js插件(兼容ie10及以上.谷歌.安卓,苹果) 强烈推荐改插件,以下介绍用法 (1)下载插件 下载路径: pdf.js (2)将下载构建后的插件放到文件中public(vue/cli 3.0) (3)在vue文件中直接使用,贴上完整代码 <template> <div class="wrap"> <iframe :src=

  • Vue-pdf实现在线预览PDF文件

    前言 在大多数项目中都会遇到在线预览PDF文件,项目使用的是element ui,使用vue-pdf实现. 安装依赖 npm install --save vue-pdf 相关参数 参数介绍: url :pdf 文件的路径,可以是本地路径,也可以是在线路径. page: 当前显示的页数,比如第一页page=1 rotate : 旋转角度,比如0就是不旋转,+90,-90 就是水平旋转. progress :当前页面的加载进度,范围是0-1 ,等于1的时候代表当前页已经完全加载完成了. page-

  • vue在线预览word、excel、pdf、txt、图片的方法实例

    目录 excel文件预览 word文件预览 pdf文件预览 一.查看word 引用mammoth.js 二.查看Excel 引用sheetjs 写的项目 1.页面 2.数据 补充:vue移动端实现word在线预览 总结 excel文件预览 word文件预览 pdf文件预览 一.查看word 引用mammoth.js 安装 npm install --save mammoth 引入import mammoth from “mammoth”; 1.页面 <div id="wordView&qu

  • 直接在线预览Word、Excel、TXT文件之ASP.NET

    具体实现过程不多说了,直接贴代码了. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Microsoft.Office.Interop.Excel; using System.Diagnostics; using System.IO; using Microsoft.Office.Interop.Word; namesp

  • Asp.Net在线预览Word文档的解决方案与思路详解

    目录 项目特点 解决方案 大致思路:先将Word文档转换Html,再预览Html. 1.Word文档转Html 2.预览 前几天有个老项目找到我,有多老呢?比我工作年限都长,见到这个项目我还得叫一声前辈. 这个项目目前使用非常稳定,十多年了没怎么更新过,现在客户想加一个小功能:在线预览Word文档. 首先想到的是用第三方的服务,例如WPS的开放平台. 刚看完文档,客户来了句,要一次性的哦,后续再付费的通通不要. 得嘞,换其他方案吧. 项目特点 Asp.Net不带Core,.NET Framewo

  • vue如何预览后端传来的二进制图片

    目录 vue预览后端传来的二进制图片 1.新建一个对话框 2.下载方法 3.转码方法 vue实现文件预览功能的前端 预览文件的前端 第一种方法: 第二种方法: vue预览后端传来的二进制图片 1.新建一个对话框 用来显示图片 <el-dialog title="" :visible.sync="imgdialog"  width="70%">   <img :src="src" alt=""

  • Vue中如何实现在线预览word文件、excel文件

    目录 实现效果 一.查看word 1.引用mammoth.js 2. 页面布局 3. 请求URL显示数据 二.查看Excel 1.引用sheetjs 2.页面布局 3.请求URL显示数据 三.项目应用:根据详情后缀分情况显示word.excel 1. 效果展示 2. 页面布局 3.调用函数展示数据 实现效果 一.查看word 1.引用mammoth.js (1)安装 npm install --save mammoth npm install --save mammoth (2)引入import

  • Android实现pdf在线预览或本地预览的方法

    最近项目中需要使用在线预览pdf,并要能实现自动播放,我想这样的需求无论如何来说都是很操蛋的 由于本人水平有限,最后讨论将项目需求改成将pdf下载到本地再实现自动播放. 接下来总结下目前能够实现pdf阅读的方案,开发当中需要根据实际需求去选择相应的方案. 1.使用Google doc支持来展示word,excel,pdf,txt(WebView方式在线预览): <span style="font-size:18px;">WebView urlWebView = (WebVi

  • Java实现PDF在线预览功能(四种方式)

    目录 Java实现PDF在线预览 Java快捷实现PDF在线预览 Java实现PDF在线预览 @RequestMapping("/preview1") public void er(HttpServletResponse response){ File file = new File("G:\\桌面\\Thymeleaf3.0中文翻译文档@www.java1234.com.pdf"); if (file.exists()){ byte[] data = null;

随机推荐