本文实例讲述了C#实现合并多个word文档的方法,是非常具有实用价值的技巧。分享给大家供大家参考。

这是在项目中客户提出的一个需求,将统一模板员工提交上来的word文档进行合并,

 

 

这就是模板,合并后的是这样的,我缩放了一下

首先是一个帮助类,帮助我们去完成合并文档操作,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Office.Interop.Word;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace FSU.API.Controllers
{
    public class WordDocumentMerger
    {
        private ApplicationClass objApp = null;
        private Document objDocLast = null;
        private Document objDocBeforeLast = null;
        public WordDocumentMerger()
        {
            objApp = new ApplicationClass();
        }
        #region 打开文件
        private void Open(string tempDoc)
        {
            object objTempDoc = tempDoc;
            object objMissing = System.Reflection.Missing.Value;

            objDocLast = objApp.Documents.Open(
               ref objTempDoc, //FileName 
               ref objMissing, //ConfirmVersions 
               ref objMissing, //ReadOnly 
               ref objMissing, //AddToRecentFiles 
               ref objMissing, //PasswordDocument 
               ref objMissing, //PasswordTemplate 
               ref objMissing, //Revert 
               ref objMissing, //WritePasswordDocument 
               ref objMissing, //WritePasswordTemplate 
               ref objMissing, //Format 
               ref objMissing, //Enconding 
               ref objMissing, //Visible 
               ref objMissing, //OpenAndRepair 
               ref objMissing, //DocumentDirection 
               ref objMissing, //NoEncodingDialog 
               ref objMissing //XMLTransform 
               );
            objDocLast.Activate();
        }
        #endregion

        #region 保存文件到输出模板
        private void SaveAs(string outDoc)
        {
            object objMissing = System.Reflection.Missing.Value;
            object objOutDoc = outDoc;
            objDocLast.SaveAs(
            ref objOutDoc, //FileName 
            ref objMissing, //FileFormat 
            ref objMissing, //LockComments 
            ref objMissing, //PassWord 
            ref objMissing, //AddToRecentFiles 
            ref objMissing, //WritePassword 
            ref objMissing, //ReadOnlyRecommended 
            ref objMissing, //EmbedTrueTypeFonts 
            ref objMissing, //SaveNativePictureFormat 
            ref objMissing, //SaveFormsData 
            ref objMissing, //SaveAsAOCELetter, 
            ref objMissing, //Encoding 
            ref objMissing, //InsertLineBreaks 
            ref objMissing, //AllowSubstitutions 
            ref objMissing, //LineEnding 
            ref objMissing //AddBiDiMarks 
            );
        }
        #endregion

        #region 循环合并多个文件(复制合并重复的文件)
        /// <summary> 
        /// 循环合并多个文件(复制合并重复的文件) 
        /// </summary> 
        /// <param name="tempDoc">模板文件</param> 
        /// <param name="arrCopies">需要合并的文件</param> 
        /// <param name="outDoc">合并后的输出文件</param> 
        public void CopyMerge(string tempDoc, string[] arrCopies, string outDoc)
        {
            object objMissing = Missing.Value;
            object objFalse = false;
            object objTarget = WdMergeTarget.wdMergeTargetSelected;
            object objUseFormatFrom = WdUseFormattingFrom.wdFormattingFromSelected;
            try
            {
                //打开模板文件 
                Open(tempDoc);
                foreach (string strCopy in arrCopies)
                {
                    objDocLast.Merge(
                    strCopy, //FileName 
                    ref objTarget, //MergeTarget 
                    ref objMissing, //DetectFormatChanges 
                    ref objUseFormatFrom, //UseFormattingFrom 
                    ref objMissing //AddToRecentFiles 
                    );
                    objDocBeforeLast = objDocLast;
                    objDocLast = objApp.ActiveDocument;
                    if (objDocBeforeLast != null)
                    {
                        objDocBeforeLast.Close(
                        ref objFalse, //SaveChanges 
                        ref objMissing, //OriginalFormat 
                        ref objMissing //RouteDocument 
                        );
                    }
                }
                //保存到输出文件 
                SaveAs(outDoc);
                foreach (Document objDocument in objApp.Documents)
                {
                    objDocument.Close(
                    ref objFalse, //SaveChanges 
                    ref objMissing, //OriginalFormat 
                    ref objMissing //RouteDocument 
                    );
                }
            }
            finally
            {
                objApp.Quit(
                ref objMissing, //SaveChanges 
                ref objMissing, //OriginalFormat 
                ref objMissing //RoutDocument 
                );
                objApp = null;
            }
        }
        /// <summary> 
        /// 循环合并多个文件(复制合并重复的文件) 
        /// </summary> 
        /// <param name="tempDoc">模板文件</param> 
        /// <param name="arrCopies">需要合并的文件</param> 
        /// <param name="outDoc">合并后的输出文件</param> 
        public void CopyMerge(string tempDoc, string strCopyFolder, string outDoc)
        {
            string[] arrFiles = Directory.GetFiles(strCopyFolder);
            CopyMerge(tempDoc, arrFiles, outDoc);
        }
        #endregion

        #region 循环合并多个文件(插入合并文件)
        /// <summary> 
        /// 循环合并多个文件(插入合并文件) 
        /// </summary> 
        /// <param name="tempDoc">模板文件</param> 
        /// <param name="arrCopies">需要合并的文件</param> 
        /// <param name="outDoc">合并后的输出文件</param> 
        public void InsertMerge(string tempDoc, string[] arrCopies, string outDoc)
        {
            object objMissing = Missing.Value;
            object objFalse = false;
            object confirmConversion = false;
            object link = false;
            object attachment = false;
            try
            {
                //打开模板文件 
                Open(tempDoc);
                foreach (string strCopy in arrCopies)
                {
                    if (!string.IsNullOrEmpty(strCopy))
                    {
                        objApp.Selection.InsertFile(
                          strCopy,
                          ref objMissing,
                          ref confirmConversion,
                          ref link,
                          ref attachment
                          );
                    }
                  
                }
                //保存到输出文件 
                SaveAs(outDoc);
                foreach (Document objDocument in objApp.Documents)
                {
                    objDocument.Close(
                    ref objFalse, //SaveChanges 
                    ref objMissing, //OriginalFormat 
                    ref objMissing //RouteDocument 
                    );
                }
            }
            finally
            {
                objApp.Quit(
                ref objMissing, //SaveChanges 
                ref objMissing, //OriginalFormat 
                ref objMissing //RoutDocument 
                );
                objApp = null;
            }
        }
        /// <summary> 
        /// 循环合并多个文件(插入合并文件) 
        /// </summary> 
        /// <param name="tempDoc">模板文件</param> 
        /// <param name="arrCopies">需要合并的文件</param> 
        /// <param name="outDoc">合并后的输出文件</param> 
        public void InsertMerge(string tempDoc, string strCopyFolder, string outDoc)
        {
            string[] arrFiles = Directory.GetFiles(strCopyFolder);
            InsertMerge(tempDoc, arrFiles, outDoc);
        }
        #endregion
    }
}

然后再去调用类方法

在控制器中添加一个辅助下载方法,该方法可以调用也可以不调用,不调用默认文件会保存至C盘地下文档文件夹中

 

 

 辅助方法

        /// <summary>
        /// 下载合成后文档,不下载会默认保存在C盘文档文件夹中
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public HttpResponseMessage GetFileFromWebApi(string name)
        {
            try
            {
                //当前主机用户名称 因为文件默认是下载到当前用户的文档文件夹中 
                string user = System.Environment.UserName;
                var FilePath = "C:\\Users\\" + user + "\\Documents\\" + name;
                var stream = new FileStream(FilePath, FileMode.Open);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = name
                };
                return response;
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }

 

第一种是会出现下载界面的代码

        /// <summary>
        /// 文件合并 需要提供文件路径
        /// </summary>
        /// <param name="filename">指定的文件名称</param>
        /// <param name="files">文件字符串</param>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public HttpResponseMessage WordMerger()
        {
            //指定合并后的文件名称
            string filename = "合并";
            //判断文件名称为空则把当前时间作为名称
            if (string.IsNullOrEmpty(filename))
            {
                filename = DateTime.Now.ToLongDateString();
            }
            //实例化 文档合成帮助类 
            WordDocumentMerger merger = new WordDocumentMerger();
            //文件路径数组
            List<string> pathstr = new List<string>();
            pathstr.Add("http://localhost:8080/appdata/demo1.docx");
            pathstr.Add("http://localhost:8080/appdata/demo2.docx");
            pathstr.Add("http://localhost:8080/appdata/demo3.docx");
            //模板路径
            string doctep ="http://localhost:8080/appdata/test.docx";
             //执行合并
            merger.InsertMerge(doctep, pathstr.ToArray(), filename);
            //下载
            return GetFileFromWebApi(filename + ".docx");
        }

 

第二种直接默认保存的方式

 

 /// <summary>
        /// 文件合并 需要提供文件路径
        /// </summary>
        /// <param name="filename">指定的文件名称</param>
        /// <param name="files">文件字符串</param>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public void WordMerger()
        {
            //指定合并后的文件名称
            string filename = "合并";
            //判断文件名称为空则把当前时间作为名称
            if (string.IsNullOrEmpty(filename))
            {
                filename = DateTime.Now.ToLongDateString();
            }
            //实例化 文档合成帮助类 
            WordDocumentMerger merger = new WordDocumentMerger();
            //文件路径数组
            List<string> pathstr = new List<string>();
            pathstr.Add("http://localhost:8080/appdata/demo1.docx");
            pathstr.Add("http://localhost:8080/appdata/demo2.docx");
            pathstr.Add("http://localhost:8080/appdata/demo3.docx");
            //模板路径
            string doctep ="http://localhost:8080/appdata/test.docx";
             //执行合并
            merger.InsertMerge(doctep, pathstr.ToArray(), filename);
        }

 

到此就分享完成了。

 

posted on 2020-09-03 11:43  迹部景吾!  阅读(246)  评论(0)    收藏  举报