指定的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. SQL技巧之排名统计

    有一道SQL笔试题是这样子的: 已知表信息如下: Department(depID, depName),depID 系编号,DepName系名 Student(stuID, name, depID)  ...

  2. GroupBox 重绘圆角边框和文字

    private void GroupBox_Paint(object sender, PaintEventArgs e) { if (sender != null && sender ...

  3. PHP的PSR-0命名标准

    PSR是Proposing a Standards Recommendation(提出标准建议)的缩写,是由PHP Framework Interoperability Group(PHP通用性框架小 ...

  4. oracle服务介绍

    按照windows 7 64位 安装oracle 11g R2中的方法成功安装Oracle 11g后,共有7个服务,这七个服务的含义分别为: 1. Oracle ORCL VSS Writer Ser ...

  5. HBase的安装与使用

    1.安装 由于还是学习阶段,所以没有在生产环境练习,就在本地建了个虚拟机进行HBase的安装. 下载地址http://www.apache.org/dyn/closer.cgi/hbase/,选择一个 ...

  6. 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解

    提醒大家,Object.prototype.toString().call(param)返回的[object class]中class首字母是大写,像JSON这种甚至都是大写,所以,大家判断的时候可以 ...

  7. 更改nginx网站根目录

    默认网站根目录为/usr/local/nginx/html,要将它改成/homw/www vi /usr/local/nginx/conf/nginx.conf 将其中的           loca ...

  8. <django中render_to_response的可选参数和使用方法>

    在django官方文档中有比较详细的介绍,在此我按照自己的理解适当的阐述一下: return render_to_response(①'my_template.html', ②my_data_dict ...

  9. 1012: [JSOI2008]最大数maxnumber

    单点更新,区间求最大值的题: 可以使用树状数组和线段树: #include<cstdio> #include<cstring> #include<algorithm> ...

  10. about js

    function: javascript jquery modernizr yepnope code organization requirejs backbonejs http://blog.csd ...