指定的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. Wooden Sticks

    Wooden Sticks Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Total ...

  2. OpenJudge/Poj 1316 Self Numbers

    1.链接地址: http://poj.org/problem?id=1316 http://bailian.openjudge.cn/practice/1316 2.题目: 总时间限制: 1000ms ...

  3. Integer ,==,int 的使用

    面试比较常见的题目:自己也经常忘记,所以就记下来了 上代码: Integer a = ,b=; Integer c = ,d=; System.out.println(a==b); System.ou ...

  4. call_user_func

    (PHP 4, PHP 5) call_user_func — 把第一个参数作为回调函数调用 mixed call_user_func ( callable $callback [, mixed $p ...

  5. C# winform关于DataGridView的一些操作

    设置字段名 设置字段值 设定单元格表示 Error图标 设定当前单元格 取得当前单元格内容 取得当前单元格的列 Index 取得当前单元格的行 Index 向下一行 向上一行 取消 DataGridV ...

  6. 【转】C# Excel 导入到 Access数据库表(winForm版)

    /// <summary> /// 获取Excel文件 /// </summary> /// <param name="sender">< ...

  7. MySQL中SQL语句的分类

    1:数据定义语言(DDL) :创建和删除数据库(CREATE DATABASE || DROP  DATABASE):2:创建.修改.重命名.删除表(CREATE  TABLE || ALTER TA ...

  8. opengl打开本地bmp图片绘制

    注意bmp图片的格式问题,32位ARGB  或者24位RGB.你所采用的素材一定要注意是多少位的就用多少位的.否则会显示错误的图片或者其他什么的错误. 代码如下 32位版本 #include < ...

  9. ModelState用法

    ModelState.AddModelError:添加错误信息 ModelState是一个字典类型,这句话的作用是向ModelState中添加一条错误信息,第一个参数是Key,第二个参数是Value. ...

  10. 一步步学习NHibernate(1)——NHibernate介绍

    请注明转载地址:http://www.cnblogs.com/arhat 第十五章 从本章开始,老魏将给大家一起学习NHibernate这个流行的ORM框架,本来老魏想要和大家一起探讨微软的EF框架的 ...