Node.js与ECharts:打造动态图表,实现Word文档自动生成

使用 Node.js 生成带动态图表的 Word 文档

在现代软件开发中,动态生成 Word 文档是一项非常常见的需求。尤其是在报告、数据分析、项目文档等方面,需要将数据以图表形式展示在 Word 文档中。而 ECharts 提供了丰富的图表类型和可定制化的功能,与 Node.js 结合使用,可以轻松地实现在 Word 文档中插入动态的 ECharts 图表。本文将介绍如何使用 Node.js 结合 ECharts 实现这一功能。

准备工作

首先,确保你已经安装了 Node.js 和 npm,然后创建一个空项目并初始化 npm:

arduino 复制代码
mkdir generate-word-docx
cd generate-word-docx
npm init -y

接下来,安装我们需要的依赖:

arduino 复制代码
npm install http fs path pizzip docxtemplater open-docxtemplater-image-module canvas echarts

编写代码

下面是生成带动态图表的 Word 文档的代码示例:

php 复制代码
javascriptCopy code
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');

// 定义替换数据
const data = {
  name1: 'John Doe',
  name2: 'Jane Smith',
  // 在这里添加柱状图数据
  image: './chart.png' // 替换为你的图片 URL 地址
};

// 定义模板文件路径
const templatePath = 'template.docx';

// 创建 HTTP 服务器
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 文档作为响应发送给客户端
    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);
  });
});

// 监听端口
const port = 3000;
server.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

// 填充 Word 文档模板并生成新的 Word 文档
function generateWord(inputPath, data, callback) {
  try {
    // 读取模板文件内容
    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) {
        // 设置图片大小,这里使用默认大小 [250, 250]
        return [250, 250];
      }
    };

    // 添加图片模块
    doc.attachModule(new ImageModule(opts));

    // 加载模板文件
    doc.loadZip(zip);

    // 设置替换数据
    doc.setData(data);

    // 渲染数据
    doc.render();

    // 生成新的 Word 文档
    const outputPath = 'output.docx';
    const buf = doc.getZip().generate({ type: 'nodebuffer' });

    // 写入新的 Word 文档
    fs.writeFileSync(outputPath, buf);

    // 调用回调函数,传递生成的 Word 文档路径
    callback(null, outputPath);
  } catch (error) {
    // 如果发生错误,则调用回调函数,并传递错误对象
    callback(error);
  }
}

// 使用 ECharts 生成柱状图图片
function generateChartImage() {
  // 创建画布
  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]
    }]
  });

  // 将画布转换为 PNG 图片并保存到文件
  const buffer = canvas.toBuffer('image/png');
  fs.writeFileSync('chart.png', buffer);
}

// 调用函数生成柱状图图片
generateChartImage();

运行代码

在命令行中执行以下命令启动服务器:

css 复制代码
bashCopy code
node your-script-name.js

服务器将在端口 3000 上启动,然后可以通过访问 http://localhost:3000 下载包含动态图表的 Word 文档。

结论

通过本文介绍的方法,你可以轻松地使用 Node.js 结合 ECharts 生成包含动态图表的 Word 文档。这种方法可以应用于各种场景,包括报告生成、数据分析、数据可视化等,为你的工作带来更多的便利和灵活性。

相关推荐
抓不住时间的沙8 小时前
Butterfly主题 5.7 导航栏添加相册同时设置相册入口密码
css·python·node.js
FungLeo9 小时前
成为全栈·Node 后端篇·通知系统:事件消费与已读态管理
node.js·成为全栈·通知系统·事件消费·已读状态管理
西瓜太郎49915 小时前
API Key 轮换不该靠“瞬间替换”:用双 Key 灰度避免线上中断
node.js·api
星辰徐哥1 天前
本地视频预览别只自己看:把Remotion动效项目发给客户远程验收
docker·ai·node.js·html·音视频·react·remotion
ID34610744201 天前
【课程设计】基于Spring Boot+Vue的校园共享无人机服务系统设计与实现-计算机毕设 附源码44219
javascript·vue.js·spring boot·python·node.js·php·课程设计
敲敲敲敲暴你脑袋2 天前
地图瓦片批量改色来啦!
node.js·gis·数据可视化
太子釢2 天前
AI 开发个人记账 App(服务端篇)
node.js·ai编程
用户64340495148513 天前
Elpis 项目构建工具与前端基建实践总结
node.js
FungLeo3 天前
成为全栈·Node 后端篇·后端测试策略:单元、集成与测试数据库
单元测试·node.js·集成测试·测试策略·成为全栈·测试数据库
FungLeo3 天前
成为全栈·Node 后端篇·评论内容安全:敏感词过滤、三态审核与级联删除
node.js·敏感词过滤·成为全栈·评论内容安全·评论审核·级联删除