1首先安装导出word需要的依赖
-- 安装 docxtemplater
npm install docxtemplater pizzip --save
-- 安装 jszip-utils
npm install jszip-utils --save
-- 安装 jszip
npm install jszip --save
-- 安装 FileSaver
npm install file-saver --save
2.然后在需要导入的页面引入
import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
3.需要准备一个word模板文件(按自己所需格式),放到项目public文件夹下,如图所示:
4.前端页面部分如图
代码如下
<div class="home-css">
<el-button style="margin: 20px" type="success" size="large" @click="outword"
>导出申请表</el-button
>
<el-card class="el-card-css">
<div style="display: flex; align-items: center; margin-top: 20px">
<span>所在部门:</span>
<el-input v-model="organ" placeholder="" clearable class="input" />
<span>姓名:</span>
<el-input v-model="name" placeholder="" clearable class="input" />
<span>性别:</span>
<el-input v-model="gender" placeholder="" clearable class="input" />
</div>
<div style="display: flex; align-items: center; margin-top: 20px">
<span>年龄:</span>
<el-input v-model="age" placeholder="" clearable class="input" />
<span>出差天数:</span>
<el-input v-model="days" placeholder="" clearable class="input" />
<span>职务:</span>
<el-input v-model="worker" placeholder="" clearable class="input" />
</div>
<div style="display: flex; align-items: center; margin-top: 20px">
<span>时间:</span>
<el-input v-model="date" placeholder="" clearable class="input" />
</div>
<div style="display: flex; align-items: center; margin-top: 20px">
<span>工作详情:</span>
<el-input
v-model="work"
maxlength="90"
show-word-limit
type="textarea"
style="width: 500px; margin-left: 20px"
/>
</div>
</el-card>
</div>
data数据如下
organ: '',
name: '',
gender: '',
age: '',
days: '',
worker: '',
date: '',
work: '',
wordData: {
title: '出差申请表',
organ: '',
name: '',
gender: '',
age: '',
days: '',
worker: '',
date: '',
work: ''
},
点击导出方法事件如下文章来源:https://uudwc.com/A/JaWZ
outword () {
this.wordData.organ = this.organ
this.wordData.name = this.name
this.wordData.gender = this.gender
this.wordData.age = this.age
this.wordData.days = this.days
this.wordData.worker = this.worker
this.wordData.date = this.date
this.wordData.why = this.why
const that = this
const word = '/出差申请表.docx'
const wordname = '出差申请表.docx'
JSZipUtils.getBinaryContent(word, function (error, content) {
if (error) {
throw error
}
const zip = new PizZip(content)
const doc = new Docxtemplater().loadZip(zip)
doc.setData({
...that.wordData
})
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
}
const out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
saveAs(out, wordname)
})
},
5.注意word文件格式一定要以.docx结尾,文件名一定要对应上,不然会报错,报错的话就看引入的word文件文章来源地址https://uudwc.com/A/JaWZ