实现效果
插件文档地址
https://docxtemplater.com/docs/get-started-node/
1. 安装对应依赖
npm install docxtemplater pizzip jszip-utils jszip file-saver --save
2.定义函数方法封装
在utils目录下创建downTable.js文件
/**
导出docx
@param { String } tempDocxPath 模板文件路径
@param { Object } data 文件中传入的数据
@param { String } fileName 导出文件名称
*/
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) => {
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
// input.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
// 抛出异常
if (error) {
throw error
}
// 创建一个JSZip实例,内容为模板的内容
const zip = new PizZip(content)
// 创建并加载docxtemplater实例对象
const doc = new docxtemplater().loadZip(zip)
// 设置模板变量的值
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. 创建docx模板
vue-cli3需要将temp.docx模板放置到public目录下,vue-cli2放置到static目录下
5. 部署
在打包前需要将模板的路径修改成exportDocx("temp.docx", data, ${that.dbNameNow}.docx
);否则会导致获取模板404