vue实现内网pdf、word、excel文件预览操作

目录

效果图:

代码实现:

1.pdf

2.word

3、excel

 整体代码


效果图:

pdf:

word:

excel:


代码实现:

1.pdf

axios.request({
    method: "GET", 
    url: '',//你的请求地址
    responseType: "arraybuffer",
    }).then((res) => {
  if (res) {
    let blob = new Blob([res.data], { type: "application/pdf;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    this.pdfurl = url;
    this.dialogVisible = true;
  } else {
    this.$notify.error({ title: "失败", message: "接口请求失败" });
  }
})
    // iframe高度
     adjustIframe() {
      var ifm = document.getElementById("pdfIframe");
      ifm.height = document.documentElement.clientHeight-50;
      ifm.width = document.documentElement.clientWidth-10;
    },

2.word

依赖

npm install docx-preview --save
 axios.request({
    method: "GET", 
    url: '',
    responseType: "arraybuffer",
}).then((res) => {
  if (res) {
  let docx = require("docx-preview");
  docx.renderAsync(res.data, this.$refs.file);
  this.dialogVisible = true;
} else {  
  this.$notify.error({ title: "失败", message: "接口请求失败" });
  }
})

3.excel

依赖:

npm install xlsx --save
axios.request({
    method: "GET", 
    url: '',
    responseType: "arraybuffer",
}).then((res) => {  
    if (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();
    });
    this.dialogVisible = true;
  } else {
       this.$notify.error({ title: "失败", message: "接口请求失败" });
   }
})
    // 设置Excel转成HTML后的样式
    setStyle4ExcelHtml() {
      const excelViewDOM = document.getElementById("excelView");
      console.log(1111111,excelViewDOM)
      if (excelViewDOM) {
        const excelViewTDNodes = excelViewDOM.getElementsByTagName("td"); // 获取的是HTMLConnection
        console.log(excelViewTDNodes);
        
        if (excelViewTDNodes) {
          const excelViewTDArr = Array.prototype.slice.call(excelViewTDNodes);
          console.log(excelViewTDArr);
          
          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");
              }
            }
          }
        }
      }
    },
.viewItemFileDialog {
  /deep/ .el-dialog__body{
    padding:0
  }
  /deep/ table {
    width: 100% !important;
    border-collapse: collapse !important;
    border-spacing: 0 !important;
    text-align: center !important;
    border: 0px !important;
    overflow-x: auto !important;
  }
 
  /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;
  }
}

 整体代码

文件展示方式:点击按钮显示弹窗 -> 弹窗预览文件

npm install xlsx --save
npm install docx-preview --save

按钮 


  {{row.fileName}}
  预览

弹窗 


    
    
      

js

preview(id,fileName) {
       //判断文件类型type
        let type = fileName.endsWith('.pdf')?"pdf":fileName.endsWith(",doc")||fileName.endsWith(".docx")?"word":fileName.endsWith('.xls')||fileName.endsWith('.xlsx')?"excel":"other"
        this.type = type
        switch (type){
        case "pdf":
          getFile(id).then((res) => {
            if (res) {
              let blob = new Blob([res.data], { type: "application/pdf;charset=utf-8" });
              const url = URL.createObjectURL(blob);
              this.pdfurl = url;
              this.dialogVisible = true;
            } else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          }).catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
          });
          return
        case "word":
          getFile(id).then((res) => {
            if (res) {
              let docx = require("docx-preview");
              docx.renderAsync(res.data, this.$refs.file);
              this.dialogVisible = true;
            }
            else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          }).catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
          });
          return
        case "excel":
          axios.request({
            method: "GET", 
            url: ''+id,
            responseType: "arraybuffer",
          }).then((res) => {
            if (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();
              });
              this.dialogVisible = true;
            } else {
              this.$notify.error({ title: "失败", message: "接口请求失败" });
            }
          }).catch(function (error) {
            this.$notify.error({ title: "失败", message: "接口请求失败" });
          });
          return
      }
    },

接口 

export function getFile(id) {
  return request({
    method: "GET", 
    url: ''+id,
    // 设置响应体类型
    // responseType: "arraybuffer", 
    responseType: "blob", 
    headers: {
      Accept: "application/octet-stream",
    },
  })
}

你可能感兴趣的:(vue,前端,vue.js,javascript)