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

如何用HTML表单数据填充Word文档?新手开发者求助

HTML表单收集数据并填充Word文档实现方案

核心思路

  • 用HTML表单收集用户输入数据
  • 借助docxtemplater库读取带占位符的Word模板,将表单数据替换到对应位置
  • 生成并下载填充完成的Word文档

实现步骤&可运行示例

1. 准备Word模板

打开Word,创建带占位符的模板,格式示例:

姓名:{name}
邮箱:{email}
电话:{phone}
留言:{message}

将文件保存为template.docx,放在HTML文件同目录下。

2. 完整代码实现

先下载以下库的本地文件,放入项目目录:

  • docxtemplater(处理Word模板)
  • pizzip(处理docx压缩格式)
  • file-saver(实现文件下载)

然后创建HTML文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>表单数据转Word</title>
    <!-- 引入本地依赖库 -->
    <script src="./docxtemplater.js"></script>
    <script src="./pizzip.js"></script>
    <script src="./pizzip-utils.js"></script>
    <script src="./FileSaver.min.js"></script>
</head>
<body>
    <form id="dataForm">
        <div>
            <label>姓名:</label>
            <input type="text" name="name" required>
        </div>
        <div>
            <label>邮箱:</label>
            <input type="email" name="email" required>
        </div>
        <div>
            <label>电话:</label>
            <input type="tel" name="phone" required>
        </div>
        <div>
            <label>留言:</label>
            <textarea name="message" rows="3"></textarea>
        </div>
        <button type="button" onclick="generateWord()">生成Word文档</button>
    </form>

    <script>
        function generateWord() {
            // 获取表单数据
            const form = document.getElementById('dataForm');
            const formData = new FormData(form);
            const data = {};
            formData.forEach((value, key) => {
                data[key] = value;
            });

            // 读取Word模板文件
            PizZipUtils.getBinaryContent('template.docx', function(error, content) {
                if (error) {
                    alert('读取模板文件失败,请检查文件路径是否正确');
                    return;
                }
                const zip = new PizZip(content);
                const doc = new window.docxtemplater(zip, {
                    paragraphLoop: true,
                    linebreaks: true,
                });

                // 替换占位符
                doc.render(data);

                // 生成Word文件并下载
                const out = doc.getZip().generate({
                    type: 'blob',
                    mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                });
                saveAs(out, '填充完成的文档.docx');
            });
        }
    </script>
</body>
</html>

3. 运行说明

  • 把template.docx、依赖库文件和上述HTML文件放在同一文件夹
  • 用本地服务器打开HTML文件(直接打开可能存在跨域问题,推荐用VSCode的Live Server插件)
  • 填写表单内容,点击按钮即可下载填充好的Word文档

注意事项

  • Word模板中的占位符{xxx}必须和表单输入框的name属性完全一致
  • 如果需要处理更复杂的内容(比如表格、图片),可以参考docxtemplater的官方文档扩展功能
  • 确保依赖库的版本兼容,示例中使用的主流稳定版本均可正常运行

内容的提问来源于stack exchange,提问作者jarvis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:15:49