C#合并多个Word文档(微软官方免费openxml接口)

g

cs 复制代码
 /// <summary>
        /// 合并多个word文档(合并到第一文件)
        /// </summary>
        /// <param name="as_word_paths">word文档完整路径</param>
        /// <param name="breakNewPage">true(默认值),合并下一个文档前,自动换页</param>
        /// <returns>无</returns> 
public void MergeWordFiles(string[] as_word_paths, bool breakNewPage = true)
        {
            var ls_first_word = as_word_paths.Length > 0 ? as_word_paths[0] : "";
            if (ls_first_word.fn_isempty())
            {
                return;
            }
            using (WordprocessingDocument doc = WordprocessingDocument.Open(ls_first_word, true))
            {
                var mainPart = doc.MainDocumentPart;
                for (var i = 1; i < as_word_paths.Length; i++)
                {
                   
                    var altChunkId = "cid_" + Guid.NewGuid().ToString().Replace("-", "");
                    var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                    //mainPart.Document.Save();
                    using (FileStream fileStream = File.Open(as_word_paths[i], FileMode.Open))
                    {
                        chunk.FeedData(fileStream);
                    }
                    var altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
                    altChunk.Id = altChunkId;
                    //添加下一页(下一个文档合并此页)
                    if (breakNewPage)
                    {
                        Paragraph newPage = new Paragraph(new Run
                         (new Break() { Type = BreakValues.Page }
                         ));
                        mainPart.Document.Append(newPage, altChunk);
                    }
                    else
                    {
                        mainPart.Document.Append(altChunk);
                    }
                    //mainPart.Document.Body.Append(altChunk);
                }
                //mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                mainPart.Document.Save();
               
            }
        }

详情了解...

相关推荐
我是坏垠10 小时前
Crypto、Cipher与Password:Java加密开发的三个核心概念
java·开发语言·python
white_ant10 小时前
JDK LTS 版本升级迁移注意事项大全
java·开发语言
Bobolink_10 小时前
跨境业务网络环境评估,“干净、一致、独享”三个关键指标
开发语言·网络·php·跨境网络·网络环境
你怎么知道我是队长10 小时前
JavaScript的变量和数据类型介绍
开发语言·javascript·ecmascript
xingke10 小时前
C 语言多文件编程:(一)头文件、extern、编译链接
c语言·开发语言·多文件
戮漠summer11 小时前
Missing Semester 计算机教育中缺失的一课 Lecture 01 Shell
开发语言·后端·scala
jinyishu_11 小时前
C++ string使用方法
开发语言·c++
EW Frontier11 小时前
三级跳突破864维动作空间——QMIX-Hierarchical多无人机协同通信方法全解析【附python代码】
开发语言·python·无人机·强化学习·通信资源分配
名字还没想好☜11 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
乐观勇敢坚强的老彭12 小时前
C++浮点数使用注意事项
开发语言·c++