實現(xiàn)效果
插件文檔地址
https://docxtemplater.com/docs/get-started-node/
1. 安裝對應(yīng)依賴
npm install docxtemplater pizzip jszip-utils jszip file-saver --save
2.定義函數(shù)方法封裝
在utils目錄下創(chuàng)建downTable.js文件
/**
導(dǎo)出docx
@param { String } tempDocxPath 模板文件路徑
@param { Object } data 文件中傳入的數(shù)據(jù)
@param { String } fileName 導(dǎo)出文件名稱
*/
import { Message } from "element-ui";
import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
export const exportDocx = (tempDocxPath, data, fileName) => {
// 讀取并獲得模板文件的二進制內(nèi)容
JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
// input.docx是模板宣蠕。我們在導(dǎo)出的時候,會根據(jù)此模板來導(dǎo)出對應(yīng)的數(shù)據(jù)
// 拋出異常
if (error) {
throw error
}
// 創(chuàng)建一個JSZip實例储矩,內(nèi)容為模板的內(nèi)容
const zip = new PizZip(content)
// 創(chuàng)建并加載docxtemplater實例對象
const doc = new docxtemplater().loadZip(zip)
// 設(shè)置模板變量的值
doc.setData({
list: data.list
})
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render()
} catch (error) {
const e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
}
console.log({
error: e
})
Message.error(e)
// The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
throw error
}
const out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
}) // Output the document using Data-URI
saveAs(out, fileName)
})
}
3. 下載
import { exportDocx } from "@/utils/downTable.js";
export default {
name: "Home",
data() {
return {
downData: [
{
"columns": [
{
"columnSize": 10,
"isNull": "YES",
"typeName": "INT",
"digits": 0,
"columnDef": "",
"remarks": "",
"columnName": "id"
},
{
"columnSize": 1024,
"isNull": "YES",
"typeName": "VARCHAR",
"digits": 0,
"columnDef": "",
"remarks": "",
"columnName": "bookname"
},
{
"columnSize": 10,
"isNull": "YES",
"typeName": "INT",
"digits": 0,
"columnDef": "",
"remarks": "",
"columnName": "size"
}
],
"dbName": "test_1",
"comment": "",
"tableName": "book"
},
{
"columns": [
{
"columnSize": 10,
"isNull": "NO",
"typeName": "INT",
"digits": 0,
"columnDef": "",
"remarks": "",
"columnName": "id"
},
{
"columnSize": 10,
"isNull": "NO",
"typeName": "INT",
"digits": 0,
"columnDef": "",
"remarks": "",
"columnName": "i"
}
],
"dbName": "test_1",
"comment": "",
"tableName": "t1"
}],
};
},
methods: {
downFile() {
var that = this;
const data = {
list: that.downData,
};
exportDocx("/temp.docx", data, `${that.dbNameNow}.docx`);
},
},
};
4. 創(chuàng)建docx模板
vue-cli3需要將temp.docx模板放置到public目錄下锌云,vue-cli2放置到static目錄下
5. 部署
在打包前需要將模板的路徑修改成exportDocx("temp.docx", data, ${that.dbNameNow}.docx
);否則會導(dǎo)致獲取模板404