Replace My Word

本文介绍如何使用C#编程来填充Word模板文件中的文本和表格内容。通过定义WordHelper类实现创建文档、替换文本、查找表格等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用C#编程修改Word模版

(2010-07-28 09:57:26)
标签:

杂谈

分类: C# Word.dot

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

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

第一步制作模版文件


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

   

  用C#编程修改Word模版

                     

 

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

用C#编程修改Word模版

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

 用C#编程修改Word模版

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

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

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

用C#编程修改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

    事件处理函数如下:

view plaincopy to clipboardprint?
private void btnQuery_Click(object sender, EventArgs e)  
{  
    string path = Application.StartupPath;  
 
    WordHelper helper = new WordHelper();  
    helper.CreateNewWordDocument(path + "//月度统计.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();  
        helper.SetCellValue("40,000");  
 
        // 第3行数据  
        helper.MoveNextRow();  
        helper.SetCellValue("3");  
 
        helper.MoveNextCell();  
        helper.SetCellValue("联想喷墨打印机");  
 
        helper.MoveNextCell();  
        helper.SetCellValue("台");  
 
        helper.MoveNextCell();  
        helper.SetCellValue("100");  
 
        helper.MoveNextCell();  
        helper.SetCellValue("80,000");  
 
    }  
 
    helper.SaveAs(path + "//200909月度统计.doc");  
    helper.Close();  

private void btnQuery_Click(object sender, EventArgs e)
{
    string path = Application.StartupPath;

    WordHelper helper = new WordHelper();
    helper.CreateNewWordDocument(path + "//月度统计.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();
        helper.SetCellValue("40,000");

        // 第3行数据
        helper.MoveNextRow();
        helper.SetCellValue("3");

        helper.MoveNextCell();
        helper.SetCellValue("联想喷墨打印机");

        helper.MoveNextCell();
        helper.SetCellValue("台");

        helper.MoveNextCell();
        helper.SetCellValue("100");

        helper.MoveNextCell();
        helper.SetCellValue("80,000");

    }

    helper.SaveAs(path + "//200909月度统计.doc");
    helper.Close();
}

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

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

第五步运行   

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

用C#编程修改Word模版


附:WordHelper.cs文件

view plaincopy to clipboardprint?
using System;  
using System.Collections.Generic;  
using System.Text;  
using System.IO;  
using Word = Microsoft.Office.Interop.Word;  
 
namespace TestWord  
{  
    class WordHelper  
    {  
        private Word.Document wDoc = null;  
        private Word.Application wApp = null;  
        public Word.Document Document  
        {  
            get { return wDoc; }  
            set { wDoc = value; }  
        }  
 
        public Word.Application Application  
        {  
            get { return wApp; }  
            set { wApp = value; }  
        } 
        #region 从模板创建新的Word文档  
        /// <summary>  
        /// 从模板创建新的Word文档  
        /// </summary>  
        /// <param name="templateName">模板文件名</param>  
        /// <returns></returns>  
        public bool CreateNewWordDocument(string templateName)  
        {  
            try 
            {  
                return CreateNewWordDocument(templateName, ref wDoc, ref wApp);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        } 
        #endregion 
 
        #region 从模板创建新的Word文档,并且返回对象Document,Application  
        /// <summary>  
        /// 从模板创建新的Word文档,  
        /// </summary>  
        /// <param name="templateName">模板文件名</param>  
        /// <param name="wDoc">返回的Word.Document对象</param>  
        /// <param name="WApp">返回的Word.Application对象</param>  
        /// <returns></returns>  
        public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref  Word.Application WApp)  
        {  
            Word.Document thisDocument = null;  
            Word.Application thisApplication = new Word.ApplicationClass();  
            thisApplication.Visible = false;  
            thisApplication.Caption = "";  
            thisApplication.Options.CheckSpellingAsYouType = false;  
            thisApplication.Options.CheckGrammarAsYouType = false;  
 
            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.  
            Object NewTemplate = false;// Optional Object. True to open the document as a template. The default value is False.  
            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.  
            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.  
 
            try 
            {  
                Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible);  
 
                thisDocument = wordDoc;  
                wDoc = wordDoc;  
                WApp = thisApplication;  
                return true;  
            }  
            catch (Exception ex)  
            {  
                string err = string.Format("创建Word文档出错,错误原因:{0}", ex.Message);  
                throw new Exception(err, ex);  
            }  
        } 
        #endregion 
 
        #region 文档另存为其他文件名  
        /// <summary>  
        /// 文档另存为其他文件名  
        /// </summary>  
        /// <param name="fileName">文件名</param>  
        /// <param name="wDoc">Document对象</param>  
        public bool SaveAs(string fileName)  
        {  
            try 
            {  
                return SaveAs(fileName, wDoc);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        } 
        #endregion 
 
        #region 文档另存为其他文件名  
        /// <summary>  
        /// 文档另存为其他文件名  
        /// </summary>  
        /// <param name="fileName">文件名</param>  
        /// <param name="wDoc">Document对象</param>  
        public static bool SaveAs(string fileName, Word.Document wDoc)  
        {  
            Object FileName = fileName; // 文档的名称。默认值是当前文件夹名和文件名。如果文档在以前没有保存过,则使用默认名称(例如,Doc1.doc)。如果已经存在具有指定文件名的文档,则会在不先提示用户的情况下改写文档。  
            Object FileFormat = Word.WdSaveFormat.wdFormatDocument; // 文档的保存格式。可以是任何 WdSaveFormat 值。要以另一种格式保存文档,请为 SaveFormat 属性指定适当的值。  
            Object LockComments = false; // 如果为 true,则锁定文档以进行注释。默认值为 false。  
            Object Password = System.Type.Missing; // 用来打开文档的密码字符串。(请参见下面的备注。)  
            Object AddToRecentFiles = false; // 如果为 true,则将该文档添加到“文件”菜单上最近使用的文件列表中。默认值为 true。  
            Object WritePassword = System.Type.Missing; // 用来保存对文件所做更改的密码字符串。(请参见下面的备注。)  
            Object ReadOnlyRecommended = false; // 如果为 true,则让 Microsoft Office Word 在打开文档时建议只读状态。默认值为 false。  
            Object EmbedTrueTypeFonts = false; //如果为 true,则将 TrueType 字体随文档一起保存。如果省略的话,则 EmbedTrueTypeFonts 参数假定 EmbedTrueTypeFonts 属性的值。  
            Object SaveNativePictureFormat = true; // 如果图形是从另一个平台(例如,Macintosh)导入的,则 true 表示仅保存导入图形的 Windows 版本。  
            Object SaveFormsData = false; // 如果为 true,则将用户在窗体中输入的数据另存为数据记录。  
            Object SaveAsAOCELetter = false; // 如果文档附加了邮件程序,则 true 表示会将文档另存为 AOCE 信函(邮件程序会进行保存)。  
            Object Encoding = System.Type.Missing; // MsoEncoding。要用于另存为编码文本文件的文档的代码页或字符集。默认值是系统代码页。  
            Object InsertLineBreaks = true; // 如果文档另存为文本文件,则 true 表示在每行文本末尾插入分行符。  
            Object AllowSubstitutions = false; //如果文档另存为文本文件,则 true 允许 Word 将某些符号替换为外观与之类似的文本。例如,将版权符号显示为 (c)。默认值为 false。  
            Object LineEnding = Word.WdLineEndingType.wdCRLF;// Word 在另存为文本文件的文档中标记分行符和换段符。可以是任何 WdLineEndingType 值。  
            Object AddBiDiMarks = true;//如果为 true,则向输出文件添加控制字符,以便保留原始文档中文本的双向布局。  
            try 
            {  
                wDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword  
                        , ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat  
                        , ref SaveFormsData, ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions  
                        , ref LineEnding, ref AddBiDiMarks);  
                return true;  
            }  
            catch (Exception ex)  
            {  
                string err = string.Format("另存文件出错,错误原因:{0}", ex.Message);  
                throw new Exception(err, ex);  
            }  
        } 
        #endregion 
 
        #region 关闭文档  
        /// <summary>  
        /// 关闭文档  
        /// </summary>  
        public void Close()  
        {  
            Close(wDoc, wApp);  
            wDoc = null;  
            wApp = null;  
        } 
        #endregion 
 
        #region 关闭文档  
        /// <summary>  
        /// 关闭文档  
        /// </summary>  
        /// <param name="wDoc">Document对象</param>  
        /// <param name="WApp">Application对象</param>  
        public static void Close(Word.Document wDoc, Word.Application WApp)  
        {  
            Object SaveChanges = Word.WdSaveOptions.wdSaveChanges;// 指定文档的保存操作。可以是下列 WdSaveOptions 值之一:wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges。  
            Object OriginalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;// 指定文档的保存格式。可以是下列 WdOriginalFormat 值之一:wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。  
            Object RouteDocument = false;// 如果为 true,则将文档传送给下一个收件人。如果没有为文档附加传送名单,则忽略此参数。  
            try 
            {  
                if (wDoc != null) wDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);  
                if (WApp != null) WApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        } 
        #endregion 
 
        #region 填充书签  
        /// <summary>  
        /// 填充书签  
        /// </summary>  
        /// <param name="bookmark">书签</param>  
        /// <param name="value">值</param>  
        public void Replace(string bookmark, string value)  
        {  
            try 
            {  
                object bkObj = bookmark;  
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)  
                {  
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();  
                }  
                else return;  
                wApp.Selection.TypeText(value);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        } 
        #endregion  
 
        public bool FindTable(string bookmarkTable)  
        {  
            try 
            {  
                object bkObj = bookmarkTable;  
                if (wApp.ActiveDocument.Bookmarks.Exists(bookmarkTable) == true)  
                {  
                    wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();  
                    return true;  
                }  
                else 
                    return false;  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
 
        public void MoveNextCell()  
        {  
            try 
            {  
                Object unit = Word.WdUnits.wdCell;  
                Object count = 1;  
                wApp.Selection.Move(ref unit, ref count);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
 
        public void SetCellValue(string value)  
        {  
            try 
            {  
                wApp.Selection.TypeText(value);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
        public void MoveNextRow()  
        {  
            try 
            {  
                Object extend = Word.WdMovementType.wdExtend;  
                Object unit = Word.WdUnits.wdCell;  
                Object count = 1;  
                wApp.Selection.MoveRight(ref unit, ref count, ref extend);  
            }  
            catch (Exception ex)  
            {  
                throw ex;  
            }  
        }  
    }  

 

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/songj1999/archive/2009/10/14/4669760.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值