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

基于OpenXML实现单模板生成多页Word文档的技术咨询

实现多页Word模板生成方案

要在生成的FinalWord.docx中添加多个与模板结构一致的页面,核心思路是克隆模板页面内容、独立修改每一页数据、追加到最终文档并添加分页符。以下是修改后的实现代码及关键说明:

修改后的完整代码

static void Create_NewWord()
{
    string documentFolder = @"C:\Users\name\Desktop\Open XML\EditWordFileUsingCsharp-main\SampleWordTemplate\{0}";
    string templatePath = string.Format(documentFolder, "Template_label.docx");
    string finalPath = string.Format(documentFolder, "FinalWord.docx");

    // 定义多页数据:每个字典对应一页的标签替换规则
    var pageDataList = new List<Dictionary<string, string>>()
    {
        new Dictionary<string, string>() { {"Power", "417 W"}, {"Voltage", "230 V"} },
        new Dictionary<string, string>() { {"Power", "500 W"}, {"Voltage", "220 V"} },
        new Dictionary<string, string>() { {"Power", "350 W"}, {"Voltage", "110 V"} }
    };

    // 创建全新的最终文档
    using (WordprocessingDocument finalDoc = WordprocessingDocument.Create(finalPath, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = finalDoc.AddMainDocumentPart();
        mainPart.Document = new Document();
        Body finalBody = mainPart.Document.AppendChild(new Body());

        foreach (var pageData in pageDataList)
        {
            // 打开模板并克隆页面内容(避免修改原始模板)
            using (WordprocessingDocument templateDoc = WordprocessingDocument.Open(templatePath, false))
            {
                IEnumerable<OpenXmlElement> templateElements = templateDoc.MainDocumentPart.Document.Body.Elements().Select(e => e.CloneNode(true));
                
                // 使用临时文档处理当前页的内容修改
                using (MemoryStream tempMem = new MemoryStream())
                {
                    using (WordprocessingDocument tempDoc = WordprocessingDocument.Create(tempMem, WordprocessingDocumentType.Document))
                    {
                        MainDocumentPart tempMainPart = tempDoc.AddMainDocumentPart();
                        tempMainPart.Document = new Document();
                        Body tempBody = tempMainPart.Document.AppendChild(new Body());

                        // 将克隆的模板元素添加到临时文档
                        foreach (var elem in templateElements)
                        {
                            tempBody.AppendChild(elem);
                        }

                        // 修改当前页的标签内容
                        WordGenerator objWord = new WordGenerator(tempDoc);
                        foreach (var kvp in pageData)
                        {
                            objWord.UpdateTextoControlWord(kvp.Key, kvp.Value);
                        }

                        // 将修改后的页面内容克隆到最终文档
                        foreach (var elem in tempBody.Elements().Select(e => e.CloneNode(true)))
                        {
                            finalBody.AppendChild(elem);
                        }
                    }
                }

                // 添加分页符(最后一页无需添加)
                if (pageData != pageDataList.Last())
                {
                    finalBody.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
                }
            }
        }

        // 保存最终文档
        mainPart.Document.Save();
    }
}

关键实现说明

  • 多页数据定义:通过pageDataList可以灵活配置每一页的替换内容,如需生成N页相同内容,可用Enumerable.Repeat重复同一字典即可。
  • 元素克隆:使用CloneNode(true)深度克隆模板的Body元素,避免直接复用元素导致的文档结构异常。
  • 临时文档隔离:每一页的修改都在独立的临时文档中进行,确保不同页面的ContentControl不会互相干扰。
  • 分页控制:通过添加Break元素(类型为BreakValues.Page)强制页面分隔,保证每页独立显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:52:50