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

2023-12-21 12:55:23

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

<a href="https://dev.csdn.net/activity?utm_source=sale_source&sale_source=yebs5WhXjQ"> <img src="https://img-home.csdnimg.cn/images/20220518054835.png" alt="CSDN开发云" /> </a>

<img src="https://img-home.csdnimg.cn/images/20220518054835.png" alt="CSDN开发云" />

文章来源:https://blog.csdn.net/LoveLearnling/article/details/135126204
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。