安装依赖:
npm install docxtemplater downloadjs
import React from 'react'; import { Document, Packer } from 'docxtemplater'; import download from 'downloadjs'; function ExportToWord() { const handleExport = () => { // 创建一个新的Word文档 const doc = new Document(); // 加载Word模板文件(template.docx) const template = fs.readFileSync('template.docx', 'binary'); doc.load(template); // 填充数据到模板中 doc.setData({ name: 'John Doe', age: 30, }); try { // 渲染Word文档 doc.render(); // 将渲染后的Word文档转换为二进制数据 const buffer = Packer.toBuffer(doc); // 下载导出的Word文档 download(buffer, 'exported_document.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'); } catch (error) { console.error('导出Word文档出错:', error); } }; return ( <div> <button onClick={handleExport}>导出Word</button> </div> ); } export default ExportToWord;