You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中如何将HTML导出为Word文档并实现点击下载

React中导出Blob为Word文档并下载

你当前的代码已经生成了Word对应的Blob对象,要实现下载,需要通过创建临时<a>标签触发浏览器下载行为。另外注意:直接把React元素传给TextRun是无效的,docx库的TextRun只接受文本内容和样式配置,而非React虚拟DOM,需要先修正这一点。

完整实现步骤

1. 修正文档构造逻辑,适配docx库要求

提取原React元素里的文本和样式,用docx库的API构造合法的文档内容:

import { Document, Packer, Paragraph, TextRun } from 'docx';

// 提取文本内容与样式(docx的字号单位为twip,10px对应20twip)
const textContent = "Your investment in the maintenance package is just , billed directly to your credit card.";
const textStyle = {
  size: 20,
  color: "#000000"
};

const generateDocx = async () => {
  const doc = new Document({
    sections: [
      {
        properties: {},
        children: [
          new Paragraph({
            children: [
              new TextRun({
                text: textContent,
                ...textStyle
              }),
            ],
          }),
        ],
      },
    ],
  });

  const blob = await Packer.toBlob(doc);
  return blob;
};

2. 添加下载处理函数

通过创建临时链接触发浏览器下载,并及时清理资源:

const downloadDocx = async () => {
  const blob = await generateDocx();
  // 生成Blob临时URL
  const url = window.URL.createObjectURL(blob);
  // 创建临时a标签
  const a = document.createElement('a');
  a.href = url;
  // 设置下载文件名
  a.download = 'maintenance-package.docx';
  // 触发下载
  document.body.appendChild(a);
  a.click();
  // 清理临时元素与URL资源
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
};

3. 绑定到按钮触发

在组件的JSX中添加按钮,绑定下载函数:

<button onClick={downloadDocx}>导出Word文档</button>

关键说明

  • 若你的HTML内容更复杂(多段落、嵌套样式等),可以考虑将HTML转换为docx库支持的节点结构,或使用html-docx-js工具直接将HTML转为docx格式的Blob。
  • 下载完成后必须调用window.URL.revokeObjectURL释放资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Muhammad Shafique Attari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:50:31