使用場(chǎng)景
前端拿到服務(wù)端數(shù)據(jù)生成 word 、excel 、pdf ,并導(dǎo)出或預(yù)覽,此處為導(dǎo)出word 參考地址
導(dǎo)出所需的依賴庫(kù)
-
docxtemplater
docxtemplater 是一種郵件合并工具,以編程方式使用并處理?xiàng)l件、循環(huán),并且可以擴(kuò)展以插入任何內(nèi)容(表格、html、圖像)。
- npm 是安裝 docxtemplater 最簡(jiǎn)單的方法
npm install docxtemplater pizzip --save
- js引入 JS 文件
-
jszip-utils
使用 AJAX 調(diào)用在提供文件的服務(wù)器上獲取文件 (HTTP GET)。如果瀏覽器支持跨域請(qǐng)求,則它們將起作用
- 使用 npm
npm install jszip-utils --save
- js引入 js文件
3.jszip
JSZip 是一個(gè)用于創(chuàng)建、讀取和編輯 .zip 文件的 javascript 庫(kù),具有可愛(ài)而簡(jiǎn)單的 API。
- 使用 npm
npm install jszip --save
- js引入 js文件
4.FileSaver
它可以利用新流的強(qiáng)大功能將數(shù)據(jù)異步直接保存到硬盤驅(qū)動(dòng)器應(yīng)用程序接口。這將支持進(jìn)度、取消和知道何時(shí)完成寫作
FileSaver.js 是在客戶端保存文件的解決方案,非常適合在客戶端生成文件的 Web 應(yīng)用程序
saveAs()
- 使用 npm
npm install file-saver --save
- js引入 js文件
頁(yè)面引入
import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
制作doc模板 并綁定數(shù)據(jù)
// 表單對(duì)象
form: {
custName: "AA", // 客戶姓名
phoneNumber: "1382324234", // 聯(lián)系方式
projectRequirement: "~", // 項(xiàng)目要求
totalPrice: 123400, // 合計(jì)報(bào)價(jià)
remark: "~~", // 備注
checkReason: '同意' // 審核備注
},
// 表格信息
tableData: [
{
number: 2, // 序號(hào)
name: "設(shè)備2", // 設(shè)備名稱
num: 2, // 數(shù)量
salePrice: 20, // 銷售單價(jià)
saleTotal: 40, // 銷售合計(jì)
remark: "啦啦啦" // 備注
}
]
exportWord: function() {
let _this = this;
// 讀取并獲得模板文件的二進(jìn)制內(nèi)容
let docxsrc = "../../static/input.docx"; //模板文件的位置 "input.docx"
JSZipUtils.getBinaryContent(docxsrc, function(error, content) {
// input.docx是模板。我們?cè)趯?dǎo)出的時(shí)候,會(huì)根據(jù)此模板來(lái)導(dǎo)出對(duì)應(yīng)的數(shù)據(jù)
// 拋出異常
if (error) {
throw error;
}
// 創(chuàng)建一個(gè)JSZip實(shí)例,內(nèi)容為模板的內(nèi)容
let zip = new PizZip(content);//PizZip JSZip
// 創(chuàng)建并加載docxtemplater實(shí)例對(duì)象
let doc = new docxtemplater().loadZip(zip);
// 設(shè)置模板變量的值
doc.setData({
..._this.form,//表頭信息
table: _this.tableData//為循環(huán)的表格
});
try {
// 用模板變量的值替換所有模板變量
doc.render();
} catch (error) {
// 拋出異常
let e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
};
console.log(JSON.stringify({ error: e }));
throw error;
}
// 生成一個(gè)代表docxtemplater對(duì)象的zip文件(不是一個(gè)真實(shí)的文件,而是在內(nèi)存中的表示)
let out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
// 將目標(biāo)文件對(duì)象保存為目標(biāo)類型的文件,并命名
saveAs(out, "報(bào)價(jià)單.docx");
});
},

doc模板
地址)