美文网首页
应用netoffice合并word的简单代码

应用netoffice合并word的简单代码

作者: windfunkey | 来源:发表于2018-01-25 21:17 被阅读0次

    应用netoffice合并word的简单代码。

    using System;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Collections.Generic;
    using System.Text;
    using NetOffice;
    using Word = NetOffice.WordApi;
    using NetOffice.WordApi.Enums;
    using Office = NetOffice.OfficeApi;
    using NetOffice.OfficeApi.Enums;
    using VBIDE = NetOffice.VBIDEApi;
    using NetOffice.VBIDEApi.Enums;
    
    namespace MyAssembly4
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] filesToMerge= new string[2];
                filesToMerge[0] = "E:/1.docx";
                filesToMerge[1] = "E:/2.docx";
                Merge(filesToMerge, "E:/3.docx");
            }
            /// <summary>
            /// A function that merges Microsoft Word Documents
            /// </summary>
            /// <param name="filesToMerge">An array of files that we want to merge</param>
            /// <param name="outputFilename">The filename of the merged document</param>
            public static void Merge(string[] filesToMerge, string outputFilename)
            {
                object outputFile = outputFilename;
                // Create  a new Word application
                Word._Application wordApplication = new Word.Application();
                try
                {
                    // Create a new file based on our template
                    Word._Document wordDocument = wordApplication.Documents.Add();
                    // Make a Word selection object.
                    Word.Selection selection = wordApplication.Selection;
                    // Loop thru each of the Word documents
                    foreach (string file in filesToMerge)
                    {
                        // Insert the files to our template
                        selection.InsertFile(file);
                    }
                    // Save the document to it's output file.
                    wordDocument.SaveAs(outputFile);
                    // Clean up!
                    wordDocument = null;
                }
                catch (Exception ex)
                {
                    //I didn't include a default error handler so i'm just throwing the error
                    throw ex;
                }
                finally
                {
                    // Finally, Close our Word application
                    wordApplication.Quit();
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:应用netoffice合并word的简单代码

          本文链接:https://www.haomeiwen.com/subject/iyebaxtx.html