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

Node.js中如何将doc2.docx追加到doc1.docx末尾?

如何在Node.js中将doc2.docx追加到doc1.docx末尾生成合并文档?

我有两个文件:doc1.docx和doc2.docx,其中doc1是模板首页,doc2是数据页。希望通过编程将doc2追加到doc1末尾,生成mergeddoc.docx,实现第一页为首页、第二页为数据页的效果(类似Word中插入文档的操作)。

我原以为这个操作难度不高,但已经卡了三天。想请教:如果该操作确实存在难度,是否有可行的替代方案?我知道可以通过Python实现类似功能,但这是最优解吗?

我尝试过以下库均未成功:

  • docx:无合并功能
  • docx-merger:已停止维护且过时,无法实现该功能
  • docx-templates:无对应功能

以下是我之前尝试的无效代码示例:

const fs = require("fs");
const path = require("path");
const os = require("os");
const createReport = require("docx-templates").default;

const saveDocument = (buffer, patientData) => {
  try {
    const downloadsPath = path.join(os.homedir(), "Downloads");
    const filename = `Report_${patientData.forename}_${
      patientData.surname
    }_${Date.now()}.docx`;
    const filePath = path.join(downloadsPath, filename);

    fs.writeFileSync(filePath, buffer);

    return filePath;
  } catch (error) {
    console.error("Error in saveDocument:", error);
    throw error;
  }
};

const generateDocument = async (data) => {
  try {
    console.log("Starting document generation...");

    const selectedGenes = data.selectedGenes;
    const geneData = data.geneData;
    const bloodResults = {
      testDetails: {
        lab: data.bloodsDetails.sendingApplication,
        receivedInLab: data.bloodsDetails.receivingFacility,
        patientId: data.bloodPatientID,
      },
      results: data.bloodResults,
    };
    const basicData = {
      patientData: data.patientData,
      clinician: data.clinicianIdentity,
    };
    const complaints = data.patientComplaints;
    const utilsData = {
      time: data.time,
      geneCount: data.selectedGenes.length,
      countBloodTests: data.bloodResults.length,
    };

    console.log("Data prepared:", {
      selectedGenes,
      geneData,
      bloodResults,
      basicData,
      complaints,
      utilsData,
    });

    const templatePath = path.join(
      __dirname,
      "../templates/base_template.docx"
    );

    if (!fs.existsSync(templatePath)) {
      throw new Error(`Template file not found at path: ${templatePath}`);
    }
    console.log(`Base template found at ${templatePath}`);

    const template = fs.readFileSync(templatePath);

    const dataForTemplate = {
      selectedGenes: [],
      geneData,
      bloodResults,
      basicData,
      complaints,
      utilsData,
    };

    for (const gene of selectedGenes) {
      const geneName = gene.geneName;
      console.log(`Processing gene: ${geneName}`);

      const geneTemplatePath = path.join(
        __dirname,
        "../templates/gene_templates",
        `${geneName}.docx`
      );

      if (!fs.existsSync(geneTemplatePath)) {
        throw new Error(
          `Gene template file not found for gene ${geneName} at path: ${geneTemplatePath}`
        );
      }
      console.log(`Gene template found at ${geneTemplatePath}`);

      const geneTemplateBuffer = fs.readFileSync(geneTemplatePath);

      dataForTemplate.selectedGenes.push({
        ...gene,
        genedoc: geneTemplateBuffer,
      });
    }

    console.log("Data prepared for main template:", dataForTemplate);

    // Generate the final report
    const buffer = await createReport({
      template,
      data: dataForTemplate,
      noSandbox: true, 
      additionalJsContext: {
        INS: (buffer) => ({
          _type: "rawXml",
          xml: buffer.toString("utf8"),
        }),
      },
    });

    console.log("Final report generated.");

    const filePath = saveDocument(buffer, data.patientData);

    console.log(`Document saved at ${filePath}`);

    return `Document generated successfully at ${filePath}`;
  } catch (error) {
    console.error("Error in generateDocument:", error);
    return `Error in generateDocument: ${error.message}`;
  }
};

module.exports = {
  generateDocument,
};

if (require.main === module) {
  (async () => {
    try {
      const data = {
        selectedGenes: [
          { geneName: "COMT", rsCode: "rs6311", combined: "TC" },
        ],
        geneData: {
          COMT: { description: "Catechol-O-methyltransferase gene" },
        },
        bloodsDetails: {
          sendingApplication: "Them",
          receivingFacility: "Us",
        },
        bloodPatientID: "123-4567",
        bloodResults: [
          {
            testCode: "HTR2A",
            testName: "HTR2A Test",
            value: "Positive",
            units: "blahs",
            referenceRange: "",
          },
        ],
        patientData: {
          patientId: "123-4567",
          title: "Mrs",
          forename: "Jane",
          surname: "Doe",
          dob: "1999-01-01",
          sex: "F",
        },
        clinicianIdentity: "Dr Who",
        patientComplaints: [
          "Decreased concentration",
          "Decreased mental sharpness",
        ],
        time: Date.now(),
      };
      const result = await generateDocument(data);
      console.log(result);
    } catch (error) {
      console.error(
        "Error running generateDocument from command line:",
        error
      );
    }
  })();
}

我也查看了其他相关方案,但均不符合需求:

  • 《How to append docx file in Golang》:语言不符
  • 《Using Node's 'Docx' to append to an existing Word doc with JS》:仅说明该库的局限性
  • 《how to append a file using docx package》:同上

目前未找到可行的Node.js替代方案,恳请各位提供解决思路。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:34:52