指定的word模版

2,生成word类

添加com Microsoft word 11.0 Object Library 引用

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
 
namespace Headfree.DefUI
{
    public class WordUtility
    {
        private object tempFile = null;
        private object saveFile = null;
        private static Word._Document wDoc = null; //word文档
        private static Word._Application wApp = null; //word进程
        private object missing = System.Reflection.Missing.Value;
 
        public WordUtility(string tempFile, string saveFile)
        {
            this.tempFile = Path.Combine(Application.StartupPath, @tempFile);
            this.saveFile = Path.Combine(Application.StartupPath, @saveFile);
        }
 
        /// <summary>
        /// 模版包含头部信息和表格,表格重复使用
        /// </summary>
        /// <param name="dt">重复表格的数据</param>
        /// <param name="expPairColumn">word中要替换的表达式和表格字段的对应关系</param>
        /// <param name="simpleExpPairValue">简单的非重复型数据</param>
        public bool GenerateWord(DataTable dt, Dictionary<string, string> expPairColumn, Dictionary<string, string> simpleExpPairValue)
        {
            if (!File.Exists(tempFile.ToString()))
            {
                MessageBox.Show(string.Format("{0}模版文件不存在,请先设置模版文件。", tempFile.ToString()));
                return false;
            }
            try
            {
                wApp = new Word.Application();
 
                wApp.Visible = false;
 
                wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing);
 
                wDoc.Activate();// 当前文档置前
 
                bool isGenerate = false;
 
                if (simpleExpPairValue != null && simpleExpPairValue.Count > 0)
                    isGenerate = ReplaceAllRang(simpleExpPairValue);
 
                // 表格有重复
                if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0)
                    isGenerate = GenerateTable(dt, expPairColumn);
 
                if (isGenerate)
                    wDoc.SaveAs(ref saveFile, 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);
 
                DisposeWord();
 
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成失败" + ex.Message);
                return false;
            }
        }
 
        /// <summary>
        /// 单个替换 模版没有重复使用的表格
        /// </summary>
        /// <param name="dc">要替换的</param>
        public bool GenerateWord(Dictionary<string, string> dc)
        {
            return GenerateWord(null, null, dc);
        }
 
 
        private bool GenerateTable(DataTable dt, Dictionary<string, string> expPairColumn)
        {
            try
            {
                int tableNums = dt.Rows.Count;
 
                Word.Table tb = wDoc.Tables[1];
 
                tb.Range.Copy();
 
                Dictionary<string, object> dc = new Dictionary<string, object>();
                for (int i = 0; i < tableNums; i++)
                {
                    dc.Clear();
 
                    if (i == 0)
                    {
                        foreach (string key in expPairColumn.Keys)
                        {
                            string column = expPairColumn[key];
                            object value = null;
                            value = dt.Rows[i][column];
                            dc.Add(key, value);
                        }
 
                        ReplaceTableRang(wDoc.Tables[1], dc);
                        continue;
                    }
 
                    wDoc.Paragraphs.Last.Range.Paste();
 
                    foreach (string key in expPairColumn.Keys)
                    {
                        string column = expPairColumn[key];
                        object value = null;
                        value = dt.Rows[i][column];
                        dc.Add(key, value);
                    }
 
                    ReplaceTableRang(wDoc.Tables[1], dc);
                }
 
 
                return true;
            }
            catch (Exception ex)
            {
                DisposeWord();
                MessageBox.Show("生成模版里的表格失败。" + ex.Message);
                return false;
            }
        }
 
        private bool ReplaceTableRang(Word.Table table, Dictionary<string, object> dc)
        {
            try
            {
                object replaceArea = Word.WdReplace.wdReplaceAll;
 
                foreach (string item in dc.Keys)
                {
                    object replaceKey = item;
                    object replaceValue = dc[item];
                    table.Range.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing,
                      ref  missing, ref missing, ref missing, ref missing, ref missing,
                      ref  replaceValue, ref replaceArea, ref missing, ref missing, ref missing,
                      ref  missing);
                }
                return true;
            }
            catch (Exception ex)
            {
                DisposeWord();
                MessageBox.Show(string.Format("{0}模版中没有找到指定的要替换的表达式。{1}", tempFile, ex.Message));
                return false;
            }
        }
 
        private bool ReplaceAllRang(Dictionary<string, string> dc)
        {
            try
            {
                object replaceArea = Word.WdReplace.wdReplaceAll;
 
                foreach (string item in dc.Keys)
                {
                    object replaceKey = item;
                    object replaceValue = dc[item];
                    wApp.Selection.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing,
                      ref  missing, ref missing, ref missing, ref missing, ref missing,
                      ref  replaceValue, ref replaceArea, ref missing, ref missing, ref missing,
                      ref  missing);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0}模版中没有找到指定的要替换的表达式。{1}", tempFile, ex.Message));
                return false;
            }
        }
 
        private void DisposeWord()
        {
            object saveOption = Word.WdSaveOptions.wdSaveChanges;
 
            wDoc.Close(ref saveOption, ref missing, ref missing);
 
            saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
 
            wApp.Quit(ref saveOption, ref missing, ref missing); //关闭Word进程
        }
    }
}

3,效果

C# 根据Word模版生成Word文件的更多相关文章

  1. asp.net根据模版生成Word小记

    最近遇到一个问题,客户提了一个新的需求,客户想要将显示在网页上的数据导出成Word进行套打,由于之前没有接触过这一块的内容,自己写的系统也没有使用这种功能,现在重头学习. 具体思路: 1.先制作Wor ...

  2. 使用word模板生成pdf文件

    使用word模板生成pdf文件 源码:UserWord

  3. 根据指定Word模板生成Word文件

    最近业务需要批量打印准考证信息 1.根据Table数据进行循环替换,每次替换的时候只替换Word中第一个Table的数据, 2.每次替换之后将Word中第一个Table数据进行复制,将复制Table和 ...

  4. 使用poi根据模版生成word文档,支持插入数据和图片

    一.制作word模版,${xxxx}是一会要替换的内容,最下面的表格是要插入数据,根据是否以$开头来判断是需要替换还是插入数据, 注意如果是需要插入数据,制作的表格模版需要一行空行,也只能有一行空行, ...

  5. JAVA Asponse.Word Office 操作神器,借助 word 模板生成 word 文档,并转化为 pdf,png 等多种格式的文件

    一,由于该 jar 包不是免费的, maven 仓库一般不会有,需要我们去官网下载并安装到本地 maven 仓库 1,用地址   https://www-evget-com/product/564  ...

  6. OpenXml操作Word的一些操作总结.无word组件生成word.

    OpenXml相对于用MS提供的COM组件来生成WORD,有如下优势: 1.相对于MS 的COM组件,因为版本带来的不兼容问题,及各种会生成WORD半途会崩溃的问题. 2.对比填满一张30多页的WOR ...

  7. OpenXml操作Word的一些操作总结.无word组件生成word.(转)

    http://www.cnblogs.com/zhouxin/p/3174936.html OpenXml相对于用MS提供的COM组件来生成WORD,有如下优势: 1.相对于MS 的COM组件,因为版 ...

  8. JAVA Freemarker + Word 模板 生成 Word 文档 (普通的变量替换,数据的循环,表格数据的循环,以及图片的东替换)

    1,最近有个需求,动态生成 Word 文当并供前端下载,网上找了一下,发现基本都是用 word 生成 xml 然后用模板替换变量的方式 1.1,这种方式虽然可行,但是生成的 xml 是在是太乱了,整理 ...

  9. java通过word模板生成word文档

    介绍 上次公司项目需要一个生成word文档的功能,有固定的模板根据业务填充数据即可,由于从来没做过,项目也比较着急于是去网上找有没有合适的工具类,找了好几种,看到其中有freeMark模板生成比较靠谱 ...

随机推荐

  1. HTML5 Video与Audio 视频与音频

    ---- 视频Video对象 - 指定视频播放地址 <video width="320" height="240" controls="cont ...

  2. Windows下Wamp装不上Memcache扩展

    windows下wamp装不上memcache扩展2015.03.20 No Comments 1,243 views用的是WAMP集成包,PHP版本5.5.12http://windows.php. ...

  3. VS2010 EntityFramework Database First

    本文演练介绍如何使用实体框架进行 Database First 开发.通过 Database First,可以从现有数据库对模型进行反向工程处理.模型存储在一个 EDMX 文件(扩展名为 .edmx) ...

  4. 面试题(C#基础)

    1>构造器Constructor不能被继承,因此不能重写Overriding,但可以被重载Overloading. 2>string[] ss=Enum.GetNames(typeof(C ...

  5. [转]MonkeyRunner在Windows下的Eclipse开发环境搭建步骤(兼解决网上Jython配置出错的问题)

    MonkeyRunner在Windows下的Eclipse开发环境搭建步骤(兼解决网上Jython配置出错的问题)   网上有一篇shangdong_chu网友写的文章介绍如何在Eclipse上配置M ...

  6. 制作Mac OS X Mavericks 安装U盘

    1. 8G+ U盘一个. 2. App Store 下载Maverics到本地(默认会下载到Applications) 2. 打开Mac OS 磁盘工具(Disk Utility),左侧选中U盘,在右 ...

  7. OpenFileDialog组件打开文件....待续

    1.常用属性 InitialDirectory           对话框的初始目录 this.openFileDialog1.InitialDirectory = "d:\\"; ...

  8. Unity3d Shader开发(四)UsePass ,GrabPass ,SubShader Tags

    (一)UsePass 命令 使用 来自另一个着色器的命名通道. Syntax 语法 UsePass "Shader/Name" 插入所有来自给定着色器中的给定名字的通道.Shade ...

  9. BZOJ 1507 [NOI2003]Editor

    Description Input 输 入文件editor.in的第一行是指令条数t,以下是需要执行的t个操作.其中: 为了使输入文件便于阅读,Insert操作的字符串中可能会插入一些回车符,请忽略掉 ...

  10. Python之添加新元素

    现在,班里有3名同学: >>> L = ['Adam', 'Lisa', 'Bart'] 今天,班里转来一名新同学 Paul,如何把新同学添加到现有的 list 中呢? 第一个办法是 ...