文章目录
- js循环导出多个word表格文档
-
- 一、文档模板编辑
- 二、安装依赖
- 三、创建导出工具类exportWord.js
- 四、调用
- 五、效果图
js循环导出多个word表格文档
- 结果案例:
一、文档模板编辑
二、安装依赖
// 实现word下载的主要依赖
npm install docxtemplater pizzip --save
// 文件操作,也可以用fs、path等模块实现
npm install jszip jszip-utils --save
// 文件存储依赖
npm install file-saver --save
三、创建导出工具类exportWord.js
import PizZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import {
saveAs } from 'file-saver'
export const exportWord = (tempDocxPath, wordData, fileName) => {
JSZipUtils.getBinaryContent(tempDocxPath, function (error, content) {
if (error) {
throw error;
}
let zip = new PizZip(content);
let doc = new Docxtemplater();
doc.loadZip(zip);
doc.setData(wordData);
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;
}
let out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
saveAs(out, fileName);
});
}
四、调用
<script lang="ts">
import {
exportWord } from '../../utils/exportWord'
export default {
name: 'DbInfo',
data (){
return{
}
},
mounted() {
},
methods: {
batchExWord(){
var dataList = [
{
"tablecnName": "部门表",
"tableName": "sys_dept",
"tableDict": [
{
"cnfield": "部门id",
"colname": "dept_id",
"datatype": "bigint(20)",
"isprimary": "Y",
"isforeign": "N",
"isonly": "Y",
"nonempty": "Y",
"defaultstr": "N",
"describe": "部门id"
},
{
"cnfield": "父部门id",
"colname": "parent_id",
"datatype": "bigint(20)",
"isprimary": "N",
"isforeign": "N",
"isonly": "N",
"nonempty": "N",
"defaultstr": "0",
"describe": "父部门id"
},
{
"cnfield": "祖级列表",
"colname": "ancestors",
"datatype": "varchar(50)",
"isprimary": "N",
"isforeign": "N",
"isonly": "N",
"nonempty": "N",
"defaultstr": "N",