一.新建WORD模板 完全安装Word 2003
新建一个word,选中视图--工具栏--窗体,点击文字型窗体域添加一个域。双击新添加的域,默认文字填写你要显示的文字,域设置--书签填入一个标签名,用于在程序中识别这个域
二.添加COM引用---Microsoft Word 11.0 Object Library
三 .添加命名空间---using Microsoft.Office.Interop.Word;
四.定义对象
ApplicationClass app = null;//定义应用程序对象 Document doc = null; //定义word文档对象 Object missing = System.Reflection.Missing.Value;//定义空变量 Object isReadOnly = false; 五.方法
1)打开word模板
- /// <summary>
- /// 打开模板word文档
- /// </summary>
- /// <param name="parFilePath">文档路径</param>
- private void OpenDocument(string parFilePath)
- {
- object filePath = parFilePath;//文档路径
- app = new ApplicationClass();
- //打开文档
- doc = app.Documents.Open(ref filePath, ref missing, ref isReadOnly, 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();//激活文档
- }
- 2.向word文档写入数据
- <PRE class=csharp name="code">/// <summary>
- /// 向word文档写入数据
- /// </summary>
- /// <param name="parLableName">域标签</param>
- /// <param name="parFillName">写入域中的内容</param>
- private void WriteIntoDocument(string parLableName, string parFillName)
- {
- object lableName = parLableName;
- Bookmark bm = doc.Bookmarks.get_Item(ref lableName);//返回标签
- bm.Range.Text = parFillName;//设置域标签的内容
- }</PRE>
- <PRE class=csharp name="code"> </PRE>
- <PRE class=csharp name="code">3.保存并关闭</PRE>
- <PRE class=csharp name="code"><PRE class=csharp name="code"> /// <summary>
- /// 保存并关闭
- /// </summary>
- /// <param name="parSaveDocPath">文档另存为的路径</param>
- private void SaveAndClose(string parSaveDocPath)
- {
- object savePath = parSaveDocPath;//文档另存为的路径
- Object saveChanges = app.Options.BackgroundSave;//关闭doc文档不提示保存
- //文档另存为
- doc.SaveAs(ref savePath, 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.Close(ref saveChanges, ref missing, ref missing);//关闭文档
- app.Quit(ref missing, ref missing, ref missing); //关闭应用程序
- }</PRE>
- </PRE>