欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现简单合并word文档的方法

程序员文章站 2022-06-30 10:22:50
本文实例讲述了c#实现简单合并word文档的方法。分享给大家供大家参考。具体如下: using system; using system.collections...

本文实例讲述了c#实现简单合并word文档的方法。分享给大家供大家参考。具体如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.reflection;
namespace demo
{
 public partial class form2 : form
 {
  public form2()
  {
   initializecomponent();
  }
  string path = @"c:\documents and settings\administrator\桌面\output.doc";
  string add = @"c:\documents and settings\administrator\桌面\file";
  private microsoft.office.interop.word.applicationclass applicationclass;
  private microsoft.office.interop.word.document doc;
  private void button1_click(object sender, eventargs e)
  {
   ex();
  }
  void ex()
  {
   open(path);
   string[] files = system.io.directory.getfiles(add);
   foreach (string s in files)
   {
    insertfile(s);
   }
   saveas(path);
  }
  /// <summary>
  /// 打开输出word文档
  /// </summary>
  /// <param name="strfilename"></param>
  public void open(string strfilename)
  {
   applicationclass = new microsoft.office.interop.word.applicationclass();
   object filename = strfilename;
   object readonly = false;
   object isvisible = true;
   object missing = system.reflection.missing.value;
   doc = applicationclass.documents.open(ref filename, ref missing, ref missing,
   ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
   ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
   doc.activate();
  }
  /// <summary>
  /// 向打开的word文档中插入word文档
  /// </summary>
  /// <param name="strfilename"></param>
  public void insertfile(string strfilename)
  {
   object missing = system.reflection.missing.value;
   object confirmconversion = false;
   object link = false;
   object attachment = false;
   applicationclass.selection.insertfile(strfilename, ref missing, ref confirmconversion, ref link, ref attachment);
   object pbreak = (int)microsoft.office.interop.word.wdbreaktype.wdsectionbreaknextpage;
   applicationclass.selection.insertbreak(ref pbreak);
  }
  /// <summary>
  /// 最后保存word文档
  /// </summary>
  /// <param name="strfilename"></param>
  public void saveas(string strfilename)
  {
   object missing = system.reflection.missing.value;
   object filename = strfilename;
   doc.saveas(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。