nodejs循环导出多个word表格文档
nodejs循环导出多个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'
/**
* 导出word,支持图片
* @param {Object} tempDocxPath 模板文件路径
* @param {Object} wordData 导出数据
* @param {Object} fileName 导出文件名
*/
export const exportWord = (tempDocxPath, wordData, fileName) => {
JSZipUtils.getBinaryContent(tempDocxPath, function (error, content) {
if (error) {
throw error;
}
// PizZip实例
let zip = new PizZip(content);
// 创建并加载docxtemplater实例
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;
}
// 生成docxtemplater对象zip文件
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",
原文地址:https://blog.csdn.net/PineSummer/article/details/144231287
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!