C# 根据Word模版生成Word文件

时间:2022-10-04 21:32:29

指定的word模版

C# 根据Word模版生成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文件

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

  1. asp&period;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&period;Word Office 操作神器,借助 word 模板生成 word 文档,并转化为 pdf,png 等多种格式的文件

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

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

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

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

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

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

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

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

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

随机推荐

  1. 敏捷组织中PMO应遵循的准则

    敏捷改变了人们的工作方式,不仅仅是开发部门,而且还包括其它的部门,例如HR.财务以及PMO等.在大多数组织中,PMO是一个控制体.它指导项目团队的规范.模板以及流程.目前,大多数的IT组织都敏捷化了. ...

  2. CodeViz代码可视化

    安装可以参见,http://blogimg.chinaunix.net/blog/upfile2/091119203927.pdf 结合pdf教程,这里说下注意事项: 1 ) 必须先安装GRAPHVI ...

  3. GnuStep使用

    gcc -o main main1.m -I/GNUstep/System/Library/Headers -fconstant-string-class=NSConstantString -L/GN ...

  4. HTML5之tabindex属性

    1 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title&g ...

  5. HBase 实战&lpar;1&rpar;--HBase的数据导入方式

    前言: 作为Hadoop生态系统中重要的一员, HBase作为分布式列式存储, 在线实时处理的特性, 备受瞩目, 将来能在很多应用场景, 取代传统关系型数据库的江湖地位. 本篇博文重点讲解HBase的 ...

  6. HW2&period;4

    import java.util.Scanner; public class Solution { public static void main(String[] args) { final dou ...

  7. iOS后向兼容:如何发现过期接口

    以4.3以下兼容性为例,在项目预编译头文件(xx.pch)中加入如下代码: #import <Availability.h> #define __AVAILABILITY_INTERNAL ...

  8. flex属性

    一.flex属性的归纳 flex-direction flex-wrap flex-flow justify-content align-items align-content 1.1 flex-di ...

  9. Python序列结构--列表&lpar;一&rpar;

    列表 列表**包含若干元素的有序连续内存空间**,当列表增加或删除元素时,**列表对象自动进行内存的扩展或收缩**,从而**保证相邻元素之间没有缝隙**.但插入和删除非尾部元素时涉及列表元素大量的移动 ...

  10. 从初始化列表和构造函数谈C&plus;&plus;的初始化机制

    来源:http://blog.csdn.net/theprinceofelf/article/details/20057359 前段时间被人问及“初始化列表和构造有什么区别?”我竟一时语塞,只好回头 ...