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();
               
            }
        }

详情了解...

相关推荐
Kalika0-042 分钟前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch44 分钟前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家1 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技1 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web1 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
龙图:会赢的1 小时前
[C语言]--编译和链接
c语言·开发语言
XKSYA(小巢校长)3 小时前
NatGo我的世界联机篇
开发语言·php
Cons.W3 小时前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手3 小时前
c++_ 多态
开发语言·c++
VBA63373 小时前
VBA信息获取与处理第三个专题第三节:工作薄在空闲后自动关闭
开发语言