文章目录
依赖版本
"vue": "^3.4.15"
"jszip-utils": "^0.1.0"
"pizzip": "^3.1.6"
"docxtemplater": "^3.46.2"
"file-saver": "^2.0.5"
最终效果
模板文件
注:word文件在顶部
表格数据结构
tableInformations: [
{
val: string,
children:[
{
courseName: string,
credits: number,
data0: string,
data1: string,
data2: string,
data3: string,
data4: string,
data5: string,
data6: string,
data7: string,
data8: string,
data9: string,
data10: string,
isCoreCourse: number,
isCourse: boolean,
isTotal: boolean,
practiceHours: string,
teachingHours: string,
totalHours: string,
totalSemester: Array<string>[11]
},
...
],
isOneLine?: boolean,
totalCredits?: number
},
...
]
代码实现
const outPutWord = async () => {
JSZipUtils.getBinaryContent(`${'/demo'}.docx`, (error, content) => {
// 抛出异常
if (error) {
throw error
}
// 创建一个PizZip实例,内容为模板的内容
const zip = new JSZip(content)
// 创建并加载docxtemplater实例对象
const doc = new Docxtemplater().loadZip(zip)
// 设置模板变量的值
doc.setData({
tableInformations: tableInformations
})
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文件(不是一个真实的文件,而是在内存中的表示)
const out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
// 将目标文件对象保存为目标类型的文件,并命名,可自定义名称
saveAs(out, '模板文件.docx')
})
}
Word语法总结
- 循环:{#forName}{/forName}
- 判断:{#ifName}{/ifName}
- 判断反面:{^ifName}{/ifName}
- 数据渲染:{dataName}
注:上述的forName、ifName和dataName应该写作对应的变量名称