c#利用Word模版生成简易报表
 
   
C#编程修改Word模版,可以生成实用的报表文件,经查询一些资料,测试成功后分享给大家,也感谢前人的探索和努力。
   
将用户提供的Word文档或者自己编写的Word文档另存为模版文件。保存类型选择“文档模版(*.dot)”。注意:默认的保存目录是Word 
指定的目录,必须切换到你的工作目录,不然很难再找到。另外,2007版本的模版后缀是*.dotx。下面举一个例子,创建一个“WordModel.dot”模版,并保存在..\Bin\Debug\
目录下
 
 
http://s15/middle/3eb67d1btac69e7b6fcfe&690
 
然后插入标签。将光标移动到需要程序填充的地方,选择菜单插入书签。
http://s12/middle/3eb67d1btac69e887fbbb&690
 
    
上图是在年前面插入一个书签,书签名为“年”。书签名是将来程序调用的依据,应当取有意义的名字。http://s8/middle/3eb67d1btac69e9b49647&690
 
      
  
如图所示,共插入了4个书签,“年”、“月”和“姓名”很清楚。“统计表”书签是为了填充表格数据。在金额后面添加的。
 
   
第二步创建一个C#项目TestWord,添加引用
    
创建一个项目,添加Word引用。
 
http://s3/middle/3eb67d1btac69ea9caed2&690
第三步 创建一个处理类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
   
事件处理函数如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
 
private void btnQuery_Click(object sender, EventArgs
e)  
{  
    string path
=
Application.StartupPath;  
 
    WordHelper
helper = new
WordHelper();  
   
helper.CreateNewWordDocument(path +
"\\WordModel.dot");  
 
   
helper.Replace("年",
"2009");  
   
helper.Replace("月", "九");  
   
helper.Replace("姓名",
"王涛");  
 
    if
(helper.FindTable("统计表"))  
   
{  
       
// 第1行数据  
       
helper.MoveNextRow();  
       
helper.SetCellValue("1");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("HP电脑");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("台");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("50");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("250,000");  
 
       
// 第2行数据  
       
helper.MoveNextRow();  
       
helper.SetCellValue("2");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("DELL笔记本");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("台");  
 
       
helper.MoveNextCell();  
       
helper.SetCellValue("10");  
 
       
helper.MoveNextCell();