使用Node.js自動生成帶動態(tài)圖表的Word文檔
使用 Node.js 生成帶動態(tài)圖表的 Word 文檔
在現(xiàn)代軟件開發(fā)中,動態(tài)生成 Word 文檔是一項非常常見的需求。尤其是在報告、數(shù)據(jù)分析、項目文檔等方面,需要將數(shù)據(jù)以圖表形式展示在 Word 文檔中。而 ECharts 提供了豐富的圖表類型和可定制化的功能,與 Node.js 結(jié)合使用,可以輕松地實現(xiàn)在 Word 文檔中插入動態(tài)的 ECharts 圖表。本文將介紹如何使用 Node.js 結(jié)合 ECharts 實現(xiàn)這一功能。
準備工作
首先,確保你已經(jīng)安裝了 Node.js 和 npm,然后創(chuàng)建一個空項目并初始化 npm:
mkdir generate-word-docx cd generate-word-docx npm init -y
接下來,安裝我們需要的依賴:
npm install http fs path pizzip docxtemplater open-docxtemplater-image-module canvas echarts
編寫代碼
下面是生成帶動態(tài)圖表的 Word 文檔的代碼示例:
const http = require('http');
const fs = require('fs');
const path = require('path');
const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');
const ImageModule = require('open-docxtemplater-image-module');
const { createCanvas } = require('canvas');
const echarts = require('echarts');
// 定義替換數(shù)據(jù)
const data = {
name1: 'John Doe',
name2: 'Jane Smith',
// 在這里添加柱狀圖數(shù)據(jù)
image: './chart.png' // 替換為你的圖片 URL 地址
};
// 定義模板文件路徑
const templatePath = 'template.docx';
// 創(chuàng)建 HTTP 服務(wù)器
const server = http.createServer((req, res) => {
// 填充 Word 文檔模板并生成新的 Word 文檔
generateWord(templatePath, data, (err, outputPath) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
// 將生成的 Word 文檔作為響應(yīng)發(fā)送給客戶端
const fileStream = fs.createReadStream(outputPath);
res.setHeader('Content-disposition', 'attachment; filename=output.docx');
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
fileStream.pipe(res);
});
});
// 監(jiān)聽端口
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
// 填充 Word 文檔模板并生成新的 Word 文檔
function generateWord(inputPath, data, callback) {
try {
// 讀取模板文件內(nèi)容
const content = fs.readFileSync(inputPath, 'binary');
// 初始化 PizZip
const zip = new PizZip(content);
// 初始化 Docxtemplater
const doc = new Docxtemplater();
// 圖片替換配置
const opts = {
centered: false,
getImage: function (tagValue, tagName) {
// 直接返回圖片地址
return fs.readFileSync(path.join(__dirname, tagValue));
},
getSize: function (img, tagValue, tagName) {
// 設(shè)置圖片大小,這里使用默認大小 [250, 250]
return [250, 250];
}
};
// 添加圖片模塊
doc.attachModule(new ImageModule(opts));
// 加載模板文件
doc.loadZip(zip);
// 設(shè)置替換數(shù)據(jù)
doc.setData(data);
// 渲染數(shù)據(jù)
doc.render();
// 生成新的 Word 文檔
const outputPath = 'output.docx';
const buf = doc.getZip().generate({ type: 'nodebuffer' });
// 寫入新的 Word 文檔
fs.writeFileSync(outputPath, buf);
// 調(diào)用回調(diào)函數(shù),傳遞生成的 Word 文檔路徑
callback(null, outputPath);
} catch (error) {
// 如果發(fā)生錯誤,則調(diào)用回調(diào)函數(shù),并傳遞錯誤對象
callback(error);
}
}
// 使用 ECharts 生成柱狀圖圖片
function generateChartImage() {
// 創(chuàng)建畫布
const canvas = createCanvas(800, 600);
const ctx = canvas.getContext('2d');
// 將 ECharts 圖表繪制到畫布上
echarts.setCanvasCreator(() => canvas);
const chart = echarts.init(canvas, null, { renderer: 'canvas' });
chart.setOption({
title: {
text: '柱狀圖示例'
},
tooltip: {},
xAxis: {
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10]
}]
});
// 將畫布轉(zhuǎn)換為 PNG 圖片并保存到文件
const buffer = canvas.toBuffer('image/png');
fs.writeFileSync('chart.png', buffer);
}
// 調(diào)用函數(shù)生成柱狀圖圖片
generateChartImage();
運行代碼
在命令行中執(zhí)行以下命令啟動服務(wù)器:
bashCopy code node your-script-name.js
服務(wù)器將在端口 3000 上啟動,然后可以通過訪問 http://localhost:3000 下載包含動態(tài)圖表的 Word 文檔。
結(jié)論
通過本文介紹的方法,你可以輕松地使用 Node.js 結(jié)合 ECharts 生成包含動態(tài)圖表的 Word 文檔。這種方法可以應(yīng)用于各種場景,包括報告生成、數(shù)據(jù)分析、數(shù)據(jù)可視化等,為你的工作帶來更多的便利和靈活性。
到此這篇關(guān)于使用Node.js自動生成帶動態(tài)圖表的Word文檔的文章就介紹到這了,更多相關(guān)Node.js生成Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
服務(wù)端nodejs抓取jsonp接口數(shù)據(jù)實現(xiàn)示例
這篇文章主要為大家介紹了服務(wù)端nodejs抓取jsonp接口數(shù)據(jù)實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
參考?EventEmitter實現(xiàn)一個簡單的訂閱發(fā)布功能函數(shù)
這篇文章主要為大家介紹了參考?EventEmitter實現(xiàn)一個簡單的訂閱發(fā)布功能函數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
Node.js 實現(xiàn) Stripe 支付的實現(xiàn)方法
本文介紹了使用Stripe支付系統(tǒng)的實現(xiàn)方法,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-11-11
Node.js開發(fā)教程之基于OnceIO框架實現(xiàn)文件上傳和驗證功能
這篇文章主要介紹了Node.js開發(fā)教程之基于OnceIO框架實現(xiàn)文件上傳和驗證的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-11-11
Node.js 中正確使用 async/await 與 Promise 
在Node.js中,async/await是ES2017引入的一種更簡潔的處理異步操作的方式,它基于Promise來進行編寫,使得異步代碼看起來更像同步代碼,易于理解和維護,這篇文章主要介紹了Node.js 中正確使用 async/await 與 Promise 對象配合,需要的朋友可以參考下2024-07-07
node.js通過axios實現(xiàn)網(wǎng)絡(luò)請求的方法
下面小編就為大家分享一篇node.js通過axios實現(xiàn)網(wǎng)絡(luò)請求的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

