vue 预览pdf/word/excel文件

文章介绍了在前端如何预览PDF、Word和Excel文件。对于PDF,使用iframe直接嵌套URL;预览Word则借助docx-preview插件,但不支持doc类型;预览Excel利用xlsx库将文件转换为HTML并设置样式。所有预览均要求后端提供文件URL。
摘要由CSDN通过智能技术生成

这里处理的都是,预览后端返回的文件地址url

1、预览pdf

直接使用iframe嵌套

<iframe v-if="url" :src="url" />

2、预览word

使用插件 docx-preview

"docx-preview": "^0.1.4"

 npm install docx-preview

页面:

<div ref="file" />

Js: 

import axios from 'axios'
let docx = require("docx-preview");

// ...
created(){
  readWordFromRemoteFile(this.url)
},
methods: {
  readWordFromRemoteFile(url){
     axios.request({
      method: "GET", 
      url,
      responseType: "blob",
    }).then(async(res) => {
      if (res) {
        // 这里需要的是blob
        docx.renderAsync(res.data, this.$refs.file);
      }
    }).catch((error) => {
      console.error(error);
    })
  },
}

备注:不支持doc类型的文件,word的预览还是建议后端做处理 

3、预览excel

使用插件 xlsx

"xlsx": "^0.16.0"

npm install xlsx

页面:

<div id="excelView" v-html="excelView" />

Js: 

// 引入
import XLSX from 'xlsx'
import axios from 'axios'  
// ...
data() {
  return {
    excelView: '',
  }
},
created(){
  readExcelFromRemoteFile(this.url)
},

methods: {
  /**
   * 预览excel
   */
  readExcelFromRemoteFile(url){
    axios.request({
      method: "GET", 
      url,
      responseType: "arraybuffer",
      }).then((res) => {  
          const workbook = XLSX.read(new Uint8Array(res.data), {
          type: "array",
        }); // 解析数据
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
        this.excelView = XLSX.utils.sheet_to_html(worksheet); // 渲染
        this.$nextTick(function () {
          // DOM加载完毕后执行,解决HTMLConnection有内容但是length为0问题。
          this.setStyle4ExcelHtml();
        });
      }).catch((error) => {
        console.error(error);
        try {
          previewFile(url)
        } catch (error) {
          console.error(error);
          this.$refs.file.innerHTML = '该文件不支持预览,请下载查看!'
        }
      })
  },
  // 设置Excel转成HTML后的样式
  setStyle4ExcelHtml() {
    const excelViewDOM = document.getElementById("excelView");
    if (excelViewDOM) {
      const excelViewTDNodes = excelViewDOM.getElementsByTagName("td"); // 获取的是HTMLConnection
      if (excelViewTDNodes) {
        const excelViewTDArr = Array.prototype.slice.call(excelViewTDNodes);
        for (const i in excelViewTDArr) {
          const id = excelViewTDArr[i].id; // 默认生成的id格式为sjs-A1、sjs-A2......
          if (id) {
            const idNum = id.replace(/[^0-9]/gi, ""); // 提取id中的数字,即行号
            if (idNum && (idNum === "1" || idNum === 1)) {
              // 第一行标题行
              excelViewTDArr[i].classList.add("class4Title");
            }
            if (idNum && (idNum === "2" || idNum === 2)) {
              // 第二行表头行
              excelViewTDArr[i].classList.add("class4TableTh");
            }
          }
        }
      }
    }
  },
}

CSS: 


/deep/ table tr td {
  border: 2px solid gray !important; 
  width: 300px !important;
  height: 33px !important;
}
/**整体样式 */
/deep/ .excel-view-container {
  background-color: #ffffff;
}
/**标题样式 */
/deep/ .class4Title {
  font-size: 22px !important;
  font-weight: bold !important;
  padding: 10px !important;
}
/**表格表头样式 */
/deep/ .class4TableTh {
  /* font-size: 14px !important; */
  font-weight: bold !important;
  padding: 2px !important;
  background-color: #ccc !important;
}

在此记录,以便下次需要

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue预览 Word 文件Excel 文件,可以通过引入第三方插件实现。 1. 首先,需要安装并引入 `office-ui-fabric-js` 和 `office-ui-fabric-react` 这两个依赖库。 ```bash npm install office-ui-fabric-js office-ui-fabric-react --save ``` 2. 然后,可以通过 `office-ui-fabric-react` 提供的 `DocumentCard` 和 `DocumentCardPreview` 组件来实现 WordExcel 文件预览。需要注意的是,这两个组件需要在 `componentDidMount` 生命周期中加载。 ```vue <template> <div> <DocumentCard> <DocumentCardPreview previewImages={[ { previewIconProps: { iconName: 'WordDocument' }, previewProps: { previewFileType: PreviewFileType.Document, previewFileUrl: 'http://example.com/word.docx' } } ]} /> </DocumentCard> <DocumentCard> <DocumentCardPreview previewImages={[ { previewIconProps: { iconName: 'ExcelWorkbook' }, previewProps: { previewFileType: PreviewFileType.Document, previewFileUrl: 'http://example.com/excel.xlsx' } } ]} /> </DocumentCard> </div> </template> <script> import { DocumentCard, DocumentCardPreview, PreviewFileType } from 'office-ui-fabric-react' export default { name: 'FilePreview', mounted () { require('office-ui-fabric-js/dist/css/fabric.min.css') require('office-ui-fabric-js/dist/css/fabric.components.min.css') }, components: { DocumentCard, DocumentCardPreview } } </script> <style scoped> /* 样式可以根据需求自行修改 */ </style> ``` 3. 最后,需要在后端将 WordExcel 文件转换为 PDF 格式,然后在前端通过 `iframe` 标签来展示 PDF 文件。 ```vue <template> <div> <iframe :src="pdfUrl" frameborder="0" width="100%" height="600"></iframe> </div> </template> <script> export default { name: 'FilePreview', data () { return { pdfUrl: '' } }, mounted () { this.getPdfUrl() }, methods: { getPdfUrl () { // 从后端获取 PDF 文件的 URL // ... this.pdfUrl = 'http://example.com/file.pdf' } } } </script> <style scoped> /* 样式可以根据需求自行修改 */ </style> ``` 以上是两种实现 WordExcel 文件预览的方法,可以根据自己的需求选择合适的方式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值