用C#编程修改Word模版

来源:互联网 发布:java交换两个变量的值 编辑:程序博客网 时间:2024/05/29 05:53

  我的一个项目中需要用C#编程修改Word模版,搜索了很多都没有说清楚,自己摸索了一下,终于完成了,在此记下来与大家分享。

包括文本替换和填充表格两种常用功能。

 

第一步制作模版文件

     将用户提供的Word文档或者自己编写的Word文档另存为模版文件。保存类型选择“文档模版(*.dot)”。注意:默认的保存目录是Word指定的目录,必须切换到你的工作目录,不然很难再找到。下面举一个例子,创建一个“月度统计.dot”模版。

   

                             

公司  年  月销售统计

姓名:  

 

序号

名称

单位

数量

金额

 

 

 

     然后插入标签。将光标移动到需要程序填充的地方,选择菜单插入书签。

插入书签

 

     上图是在年前面插入一个书签,书签名为“年”。书签名是将来程序调用的依据,应当取有意义的名字。

 书签

 

     如图所示,共插入了4个书签,“年”、“月”和“姓名”很清楚。“统计表”书签是为了填充表格数据。在金额后面添加的。

 

 

第二步创建一个C#项目TestWord,添加引用

 

     创建一个项目,添加Word引用。

 添加引用添加word引用

 

 

第三步 创建一个处理类WordHelper

       为了复用,专门定义一个处理类WordHelper。主要接口函数包括:

       (1)从模版创建文件

public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref  Word.Application WApp)

       (2)另存为

public static bool SaveAs(string fileName, Word.Document wDoc)

       (3)关闭

public static void Close(Word.Document wDoc, Word.Application WApp)

       (4)填充书签

public void Replace(string bookmark, string value)

       (5)查找表格

public bool FindTable(string bookmarkTable)

       (6)移动到下一个单元格

public void MoveNextCell()

       (7)填充单元格内容

public void SetCellValue(string value)

       (8)移动到下一行

public void MoveNextRow()

       代码比较长,在后面列出。

 

第四步 在窗体上放置一个“查询”按钮btnQuery

    事件处理函数如下:

 

[c-sharp] view plaincopy
  1. private void btnQuery_Click(object sender, EventArgs e)  
  2. {  
  3.     string path = Application.StartupPath;  
  4.   
  5.     WordHelper helper = new WordHelper();  
  6.     helper.CreateNewWordDocument(path + "//月度统计.dot");  
  7.   
  8.     helper.Replace("年""2009");  
  9.     helper.Replace("月""九");  
  10.     helper.Replace("姓名""王涛");  
  11.   
  12.     if (helper.FindTable("统计表"))  
  13.     {  
  14.         // 第1行数据  
  15.         helper.MoveNextRow();  
  16.         helper.SetCellValue("1");  
  17.   
  18.         helper.MoveNextCell();  
  19.         helper.SetCellValue("HP电脑");  
  20.   
  21.         helper.MoveNextCell();  
  22.         helper.SetCellValue("台");  
  23.   
  24.         helper.MoveNextCell();  
  25.         helper.SetCellValue("50");  
  26.   
  27.         helper.MoveNextCell();  
  28.         helper.SetCellValue("250,000");  
  29.   
  30.         // 第2行数据  
  31.         helper.MoveNextRow();  
  32.         helper.SetCellValue("2");  
  33.   
  34.         helper.MoveNextCell();  
  35.         helper.SetCellValue("DELL笔记本");  
  36.   
  37.         helper.MoveNextCell();  
  38.         helper.SetCellValue("台");  
  39.   
  40.         helper.MoveNextCell();  
  41.         helper.SetCellValue("10");  
  42.   
  43.         helper.MoveNextCell();  
  44.         helper.SetCellValue("40,000");  
  45.   
  46.         // 第3行数据  
  47.         helper.MoveNextRow();  
  48.         helper.SetCellValue("3");  
  49.   
  50.         helper.MoveNextCell();  
  51.         helper.SetCellValue("联想喷墨打印机");  
  52.   
  53.         helper.MoveNextCell();  
  54.         helper.SetCellValue("台");  
  55.   
  56.         helper.MoveNextCell();  
  57.         helper.SetCellValue("100");  
  58.   
  59.         helper.MoveNextCell();  
  60.         helper.SetCellValue("80,000");  
  61.   
  62.     }  
  63.   
  64.     helper.SaveAs(path + "//200909月度统计.doc");  
  65.     helper.Close();  
  66. }  

 

      可以看到,在书签处填写内容比较简单,一个函数完成了。填充表格会复杂一些,模仿了人的动作。首先定位到标题的最后,移动到下一行的第一个单元,填充数据,然后移动到下一格,再填充,再移动。直到最后一列,再移动到下一行。

      参照上面的例子,很容易从数据库中读出数据填充到表格中。

 

第五步 运行   

    将模版文件拷贝到可执行文件目录下,运行,点击查询按钮,得到输出的文档“200909月度统计.doc”

 

公司 2009 年 九 月销售统计

姓名: 王涛

 

序号

名称

单位

数量

金额

1

HP电脑

50

250,000

2

DELL笔记本

10

40,000

3

联想喷墨打印机

100

80,000

 

 
附:WordHelper.cs文件

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.IO;  
  5. using Word = Microsoft.Office.Interop.Word;  
  6.   
  7. namespace TestWord  
  8. {  
  9.     class WordHelper  
  10.     {  
  11.         private Word.Document wDoc = null;  
  12.         private Word.Application wApp = null;  
  13.         public Word.Document Document  
  14.         {  
  15.             get { return wDoc; }  
  16.             set { wDoc = value; }  
  17.         }  
  18.   
  19.         public Word.Application Application  
  20.         {  
  21.             get { return wApp; }  
  22.             set { wApp = value; }  
  23.         }  
  24.         #region 从模板创建新的Word文档  
  25.         /// <summary>  
  26.         /// 从模板创建新的Word文档  
  27.         /// </summary>  
  28.         /// <param name="templateName">模板文件名</param>  
  29.         /// <returns></returns>  
  30.         public bool CreateNewWordDocument(string templateName)  
  31.         {  
  32.             try  
  33.             {  
  34.                 return CreateNewWordDocument(templateName, ref wDoc, ref wApp);  
  35.             }  
  36.             catch (Exception ex)  
  37.             {  
  38.                 throw ex;  
  39.             }  
  40.         }  
  41.         #endregion  
  42.  
  43.         #region 从模板创建新的Word文档,并且返回对象Document,Application  
  44.         /// <summary>  
  45.         /// 从模板创建新的Word文档,  
  46.         /// </summary>  
  47.         /// <param name="templateName">模板文件名</param>  
  48.         /// <param name="wDoc">返回的Word.Document对象</param>  
  49.         /// <param name="WApp">返回的Word.Application对象</param>  
  50.         /// <returns></returns>  
  51.         public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref  Word.Application WApp)  
  52.         {  
  53.             Word.Document thisDocument = null;  
  54.             Word.Application thisApplication = new Word.ApplicationClass();  
  55.             thisApplication.Visible = false;  
  56.             thisApplication.Caption = "";  
  57.             thisApplication.Options.CheckSpellingAsYouType = false;  
  58.             thisApplication.Options.CheckGrammarAsYouType = false;  
  59.   
  60.             Object Template = templateName;// Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used.  
  61.             Object NewTemplate = false;// Optional Object. True to open the document as a template. The default value is False.  
  62.             Object DocumentType = Word.WdNewDocumentType.wdNewBlankDocument; // Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument.  
  63.             Object Visible = true;//Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True.  
  64.   
  65.             try  
  66.             {  
  67.                 Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible);  
  68.   
  69.                 thisDocument = wordDoc;  
  70.                 wDoc = wordDoc;  
  71.                 WApp = thisApplication;  
  72.                 return true;  
  73.             }  
  74.             catch (Exception ex)  
  75.             {  
  76.                 string err = string.Format("创建Word文档出错,错误原因:{0}", ex.Message);  
  77.                 throw new Exception(err, ex);  
  78.             }  
  79.         }  
  80.         #endregion  
  81.  
  82.         #region 文档另存为其他文件名  
  83.         /// <summary>  
  84.         /// 文档另存为其他文件名  
  85.         /// </summary>  
  86.         /// <param name="fileName">文件名</param>  
  87.         /// <param name="wDoc">Document对象</param>  
  88.         public bool SaveAs(string fileName)  
  89.         {  
  90.             try  
  91.             {  
  92.                 return SaveAs(fileName, wDoc);  
  93.             }  
  94.             catch (Exception ex)  
  95.             {  
  96.                 throw ex;  
  97.             }  
  98.         }  
  99.         #endregion  
  100.  
  101.         #region 文档另存为其他文件名  
  102.         /// <summary>  
  103.         /// 文档另存为其他文件名  
  104.         /// </summary>  
  105.         /// <param name="fileName">文件名</param>  
  106.         /// <param name="wDoc">Document对象</param>  
  107.         public static bool SaveAs(string fileName, Word.Document wDoc)  
  108.         {  
  109.             Object FileName = fileName; // 文档的名称。默认值是当前文件夹名和文件名。如果文档在以前没有保存过,则使用默认名称(例如,Doc1.doc)。如果已经存在具有指定文件名的文档,则会在不先提示用户的情况下改写文档。  
  110.             Object FileFormat = Word.WdSaveFormat.wdFormatDocument; // 文档的保存格式。可以是任何 WdSaveFormat 值。要以另一种格式保存文档,请为 SaveFormat 属性指定适当的值。  
  111.             Object LockComments = false// 如果为 true,则锁定文档以进行注释。默认值为 false。  
  112.             Object Password = System.Type.Missing; // 用来打开文档的密码字符串。(请参见下面的备注。)  
  113.             Object AddToRecentFiles = false// 如果为 true,则将该文档添加到“文件”菜单上最近使用的文件列表中。默认值为 true。  
  114.             Object WritePassword = System.Type.Missing; // 用来保存对文件所做更改的密码字符串。(请参见下面的备注。)  
  115.             Object ReadOnlyRecommended = false// 如果为 true,则让 Microsoft Office Word 在打开文档时建议只读状态。默认值为 false。  
  116.             Object EmbedTrueTypeFonts = false//如果为 true,则将 TrueType 字体随文档一起保存。如果省略的话,则 EmbedTrueTypeFonts 参数假定 EmbedTrueTypeFonts 属性的值。  
  117.             Object SaveNativePictureFormat = true// 如果图形是从另一个平台(例如,Macintosh)导入的,则 true 表示仅保存导入图形的 Windows 版本。  
  118.             Object SaveFormsData = false// 如果为 true,则将用户在窗体中输入的数据另存为数据记录。  
  119.             Object SaveAsAOCELetter = false// 如果文档附加了邮件程序,则 true 表示会将文档另存为 AOCE 信函(邮件程序会进行保存)。  
  120.             Object Encoding = System.Type.Missing; // MsoEncoding。要用于另存为编码文本文件的文档的代码页或字符集。默认值是系统代码页。  
  121.             Object InsertLineBreaks = true// 如果文档另存为文本文件,则 true 表示在每行文本末尾插入分行符。  
  122.             Object AllowSubstitutions = false//如果文档另存为文本文件,则 true 允许 Word 将某些符号替换为外观与之类似的文本。例如,将版权符号显示为 (c)。默认值为 false。  
  123.             Object LineEnding = Word.WdLineEndingType.wdCRLF;// Word 在另存为文本文件的文档中标记分行符和换段符。可以是任何 WdLineEndingType 值。  
  124.             Object AddBiDiMarks = true;//如果为 true,则向输出文件添加控制字符,以便保留原始文档中文本的双向布局。  
  125.             try  
  126.             {  
  127.                 wDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword  
  128.                         , ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat  
  129.                         , ref SaveFormsData, ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions  
  130.                         , ref LineEnding, ref AddBiDiMarks);  
  131.                 return true;  
  132.             }  
  133.             catch (Exception ex)  
  134.             {  
  135.                 string err = string.Format("另存文件出错,错误原因:{0}", ex.Message);  
  136.                 throw new Exception(err, ex);  
  137.             }  
  138.         }  
  139.         #endregion  
  140.  
  141.         #region 关闭文档  
  142.         /// <summary>  
  143.         /// 关闭文档  
  144.         /// </summary>  
  145.         public void Close()  
  146.         {  
  147.             Close(wDoc, wApp);  
  148.             wDoc = null;  
  149.             wApp = null;  
  150.         }  
  151.         #endregion  
  152.  
  153.         #region 关闭文档  
  154.         /// <summary>  
  155.         /// 关闭文档  
  156.         /// </summary>  
  157.         /// <param name="wDoc">Document对象</param>  
  158.         /// <param name="WApp">Application对象</param>  
  159.         public static void Close(Word.Document wDoc, Word.Application WApp)  
  160.         {  
  161.             Object SaveChanges = Word.WdSaveOptions.wdSaveChanges;// 指定文档的保存操作。可以是下列 WdSaveOptions 值之一:wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges。  
  162.             Object OriginalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;// 指定文档的保存格式。可以是下列 WdOriginalFormat 值之一:wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。  
  163.             Object RouteDocument = false;// 如果为 true,则将文档传送给下一个收件人。如果没有为文档附加传送名单,则忽略此参数。  
  164.             try  
  165.             {  
  166.                 if (wDoc != null) wDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);  
  167.                 if (WApp != null) WApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);  
  168.             }  
  169.             catch (Exception ex)  
  170.             {  
  171.                 throw ex;  
  172.             }  
  173.         }  
  174.         #endregion  
  175.  
  176.         #region 填充书签  
  177.         /// <summary>  
  178.         /// 填充书签  
  179.         /// </summary>  
  180.         /// <param name="bookmark">书签</param>  
  181.         /// <param name="value">值</param>  
  182.         public void Replace(string bookmark, string value)  
  183.         {  
  184.             try  
  185.             {  
  186.                 object bkObj = bookmark;  
  187.                 if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)  
  188.                 {  
  189.                     wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();  
  190.                 }  
  191.                 else return;  
  192.                 wApp.Selection.TypeText(value);  
  193.             }  
  194.             catch (Exception ex)  
  195.             {  
  196.                 throw ex;  
  197.             }  
  198.         }  
  199.         #endregion  
  200.   
  201.         public bool FindTable(string bookmarkTable)  
  202.         {  
  203.             try  
  204.             {  
  205.                 object bkObj = bookmarkTable;  
  206.                 if (wApp.ActiveDocument.Bookmarks.Exists(bookmarkTable) == true)  
  207.                 {  
  208.                     wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();  
  209.                     return true;  
  210.                 }  
  211.                 else  
  212.                     return false;  
  213.             }  
  214.             catch (Exception ex)  
  215.             {  
  216.                 throw ex;  
  217.             }  
  218.         }  
  219.   
  220.         public void MoveNextCell()  
  221.         {  
  222.             try  
  223.             {  
  224.                 Object unit = Word.WdUnits.wdCell;  
  225.                 Object count = 1;  
  226.                 wApp.Selection.Move(ref unit, ref count);  
  227.             }  
  228.             catch (Exception ex)  
  229.             {  
  230.                 throw ex;  
  231.             }  
  232.         }  
  233.   
  234.         public void SetCellValue(string value)  
  235.         {  
  236.             try  
  237.             {  
  238.                 wApp.Selection.TypeText(value);  
  239.             }  
  240.             catch (Exception ex)  
  241.             {  
  242.                 throw ex;  
  243.             }  
  244.         }  
  245.         public void MoveNextRow()  
  246.         {  
  247.             try  
  248.             {  
  249.                 Object extend = Word.WdMovementType.wdExtend;  
  250.                 Object unit = Word.WdUnits.wdCell;  
  251.                 Object count = 1;  
  252.                 wApp.Selection.MoveRight(ref unit, ref count, ref extend);  
  253.             }  
  254.             catch (Exception ex)  
  255.             {  
  256.                 throw ex;  
  257.             }  
  258.         }  
  259.     }  
  260. }  
原创粉丝点击