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

详情了解...

相关推荐
ghie90901 小时前
MATLAB/Simulink水箱水位控制系统实现
开发语言·算法·matlab
cs麦子2 小时前
C语言--详解--指针--上
c语言·开发语言
像风一样自由20202 小时前
Go语言入门指南-从零开始的奇妙之旅
开发语言·后端·golang
CoderYanger3 小时前
前端基础——CSS练习项目:百度热榜实现
开发语言·前端·css·百度·html·1024程序员节
虾..4 小时前
C++ 哈希
开发语言·c++·哈希算法
liu****4 小时前
14.日志封装和线程池封装
linux·开发语言·c++
青青草原羊村懒大王4 小时前
python基础知识三
开发语言·python
蒲公英10014 小时前
在wps软件的word中使用js宏命令设置表格背景色
javascript·word·wps
封奚泽优4 小时前
word导入样式模版
word
将编程培养成爱好4 小时前
C++ 设计模式《统计辅助功能》
开发语言·c++·设计模式·访问者模式