欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue項目中如何將數(shù)據(jù)導(dǎo)出為word文檔

 更新時間:2025年03月28日 09:26:11   作者:想太多會累i  
這篇文章主要介紹了vue項目中如何將數(shù)據(jù)導(dǎo)出為word文檔問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

Vue項目中將后端獲取數(shù)據(jù)循環(huán)導(dǎo)出為Word文檔

首先安裝需要的項目依賴

這里給大家推薦一套我親測可用的配置:

npm install file-saver@2.0.5 --save
npm install docxtemplater@3.26.3 --save
npm install jszip@3.7.1 --save
npm install jszip-utils@0.1.0 --save
npm install pizzip@3.1.1 --save

這里是我的項目依賴

在.vue文件中加載依賴

import Docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";

編寫exportWord方法

// 打印文檔處理
    exportWord() {
      const that = this;
      // 讀取并獲得模板文件的二進制內(nèi)容
      JSZipUtils.getBinaryContent("./service.docx", function (error, content) {
        // gy-agree-service.docx是模板。我們在導(dǎo)出的時候,會根據(jù)此模板來導(dǎo)出對應(yīng)的數(shù)據(jù)
        // 拋出異常
        if (error) {
          throw error;
        }
        // 創(chuàng)建一個PizZip實例,內(nèi)容為模板的內(nèi)容
        const zip = new PizZip(content);
        // 創(chuàng)建并加載docxtemplater實例對象
        const doc = new Docxtemplater().loadZip(zip);
        // 設(shè)置模板變量的值
        doc.setData({
          date: that.timeVal,
          isTable: that.rightTable, // 文檔中循環(huán)數(shù)據(jù)
          loseTable: that.errorTable, // 文檔中循環(huán)的數(shù)據(jù)
        });
        try {
          // 用模板變量的值替換所有模板變量
          doc.render();
        } catch (error) {
          // 拋出異常
          const e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          };
          console.log(JSON.stringify({ error: e }));
          throw error;
        }

        // 生成一個代表docxtemplater對象的zip文件(不是一個真實的文件,而是在內(nèi)存中的表示)
        const out = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        // 將目標(biāo)文件對象保存為目標(biāo)類型的文件,并命名
        saveAs(out, that.timeVal + "做題記錄表.docx");
      });
    },

然后編寫.docx的word文檔 命名為service.docx

{date}口算題做題結(jié)果
正確題:
{#isTable}
{num1} {symbol} {num2} =   {result}  {answer}  {isRight}
{/isTable}


錯誤題:
{#loseTable}
{num1} {symbol} {num2} =   {result}  {answer}  {isRight}
{/loseTable}

標(biāo)簽里面是數(shù)組中對應(yīng)的屬性

然后將這個文件放置在vue項目中的public文件下:

然后調(diào)用exportWord方法就可以將數(shù)據(jù)直接導(dǎo)出展示

導(dǎo)出的文件:

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論