[Vue project practice] Realize online preview of word files and excel files

JUST DO IT

Table of contents

1. View word

1. Reference mammoth.js

2. Page layout

3. Request URL to display data

2. View Excel

         1. Reference sheetjs

2. Page layout

3. Request URL to display data

3. Project application: display word and excel according to the details and suffixes

         1. Effect display

2. Page layout

3. Call the function to display the data


Realize the effect:

 1. View word

1. Reference mammoth.js

(1) Install npm install --save mammoth

npm install --save mammoth

 (2) Introduce import mammoth from "mammoth";

import mammoth from "mammoth";

2. Page layout

<!-- word查看详情 -->
<div id="wordView" v-html="vHtml"/></div>

 3. Request URL to display data

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();
    },
}

2. View Excel

1. Reference sheetjs

(1) Install npm install --save xlsx

npm install --save xlsx

(2) Introduce import XLSX from "xlsx";

import XLSX from "xlsx";

2. Page layout

<!-- 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>

3. Request URL to display data

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);
    },
}

3. Project application: display word and excel according to the details and suffixes

1. Effect display

Scenario description: Click the view button to display the data in a pop-up box

2. Page layout

<div :style="'border:1px dashed;width:100%;height:300px;overflow:scroll'">
  <!-- word查看详情 -->
  <div id="wordView" v-html="vHtml" v-if="isWord" />
  <!-- 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>
  <!-- <div v-else></div> -->
</div>

 3. Call the function to display the data

Determine which form to use based on the file suffix in the row

data() {
  return {
    // 显示word excel
    vHtml: "",
    wordURL: "",
    isWord: "",
    fileType: "", // 1 word(.docx .doc) 2 excel(.xlsx .xsl) 3 其他()
    excelData: [],
    workbook: {},
    excelURL: "", //文件地址,看你对应怎末获取、赋值
  };
},
methods:{
   // 查看详情=列表操作
   // <el-button type="text" @click="handleDetail(scope.row)" v-if="!scope.row.havePassword">查看</el-button>
   handleDetail(row) {
      console.log(row, "查看row");
      this.tzOpen = true;
      this.detailForm = row;
      if (row.suffix === "docx" || row.suffix === "doc") {
        // this.fileType = 1;
        this.isWord = 1;
        // this.wordURL = row.url;
        this.readExcelFromRemoteFile(row.url);
      } else if (row.suffix === "xlsx" || row.suffix === "xls") {
        // this.fileType = 2;
        this.isWord = 0;
        // this.excelURL = row.url;
        this.readWorkbookFromRemoteFile(row.url);
      }
    },
// 在线查看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();
    },
    // 在线查看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();
    },
    getTable(sheetName) {
      console.log(sheetName);
      var worksheet = this.workbook.Sheets[sheetName];
      this.excelData = XLSX.utils.sheet_to_json(worksheet);
      console.log(this.excelData);
    },
}
#table {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 60px;
  border: 1px solid #ebebeb;
  padding: 20px;
  width: 100%;
  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;
  }
}

Reference link: Vue word preview, excel preview, pdf preview_ If you have any questions, please follow the public account: front-end research institute background input question reply-CSDN blog_vue word preview

Guess you like

Origin blog.csdn.net/Sabrina_cc/article/details/121979484