1.占位符替换模板导出(只适用于word中含有表格形式的):

/// <summary>
/// 使用替换模板进行到处word文件
/// </summary>
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)
{
tempFile = System.Web.HttpContext.Current.Server.MapPath(tempFile);
saveFile = System.Web.HttpContext.Current.Server.MapPath(saveFile);
this.tempFile = tempFile;// Path.Combine(Application.StartupPath, @tempFile);
this.saveFile = 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()))
{ 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)
{
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; for (int j = 1; j <= wDoc.Tables.Count; j++)
{
Word.Table tb = wDoc.Tables[j]; 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[j], 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[j], dc);
}
} return true;
}
catch (Exception ex)
{
DisposeWord();
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(); 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)
{
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进程
}
}

  demo:

 #region 动态创建DataTable数据
DataTable tblDatas = new DataTable("Datas");
DataColumn dc = null;
//赋值给dc,是便于对每一个datacolumn的操作
dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
dc.AutoIncrement = true;//自动增加
dc.AutoIncrementSeed = 1;//起始为1
dc.AutoIncrementStep = 1;//步长为1
dc.AllowDBNull = false;//
dc = tblDatas.Columns.Add("NO", Type.GetType("System.String"));//////1
DataRow newRow;
newRow = tblDatas.NewRow();
newRow["NO"] = info.NO;////////房屋座落地址 2--info实体类 tblDatas.Rows.Add(newRow);
#endregion
#region word要替换的表达式和表格字段的对应关系
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("$id$", "NO");//////////3
#endregion
string tempFile = "~/Doc/doc.doc";
string saveFile = "~/Doc/" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".doc";
WordUtility w = new WordUtility(tempFile, saveFile);
w.GenerateWord(tblDatas, dic, null);

word模板导出的几种方式:第一种:占位符替换模板导出(只适用于word中含有表格形式的)的更多相关文章

  1. 关于.net导出数据到excel/word【占位符替换】

    1]excel的占位符替换 效果如图 关键代码: ///savedFilePath需要保存的路径 templateDocPath模板路径 替换的关键字和值 格式 [姓名]$%$小王 public st ...

  2. Android提交数据到服务器的两种方式四种方法

    本帖最后由 yanghe123 于 2012-6-7 09:58 编辑 Android应用开发中,会经常要提交数据到服务器和从服务器得到数据,本文主要是给出了利用http协议采用HttpClient方 ...

  3. 数据库时间内接受的是lang类型的时间 分为三种字段 第一种只存日期 第二种存日期+时间 第三种时间戳

    数据库时间内接受的是lang类型的时间 分为三种字段 第一种只存日期 第二种存日期+时间 第三种时间戳

  4. C# 利用占位符替换word中的字符串和添加图片

    利用占位符替换word中的字符串和添加图片   ///<summary>         /// 替换word模板文件内容,包括表格中内容         /// 调用如下:WordStr ...

  5. word模板导出的几种方式:第二种:C#通过模板导出Word(文字,表格,图片) 占位符替换

    原文出处:https://www.cnblogs.com/ilefei/p/3508463.html 一:模板的创建   (注意文件后缀只能是.docx或.doct) 在需要位置 插入-文档部件-域, ...

  6. 创建对象的一种方式&一种继承机制(代码实例)

    /* 创建对象的一种方式:混合的构造函数/原型方式, *用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法) */ function People(sname){ this.nam ...

  7. vue组件通信的几种方式

    最近用vue开发项目,记录一下vue组件间通信几种方式 第一种,父子组件通信 一.父组件向子组件传值 1.创建子组件,在src/components/文件夹下新建一个Child.vue 2.Child ...

  8. flink01--------1.flink简介 2.flink安装 3. flink提交任务的2种方式 4. 4flink的快速入门 5.source 6 常用算子(keyBy,max/min,maxBy/minBy,connect,union,split+select)

    1. flink简介 1.1 什么是flink Apache Flink是一个分布式大数据处理引擎,可以对有限数据流(如离线数据)和无限流数据及逆行有状态计算(不太懂).可以部署在各种集群环境,对各种 ...

  9. spring配置属性的两种方式

    spring配置属性有两种方式,第一种方式通过context命名空间中的property-placeholder标签 <context:property-placeholder location ...

随机推荐

  1. 使用npm 下载 cnpm

    在vue终端使用npm 1. 下载安装node.js 在node.js中有集成npm 2. 可以在终端中使用 node -v / npm -v 来查看安装的node/npm 的版本号 使用npm 安装 ...

  2. ROS串口通信

    身处机器人行业,不想一直只做低端的单片机控制,老是待在舒适区,所以一直都想学一下ROS系统,但看了几个月资料后,感觉还是云里雾里,似懂非懂,感念似乎都很清楚,但要实际去做,却又感觉无从下手. 于是想先 ...

  3. 2018-2019-2 网络对抗技术 20165317 Exp4 恶意代码分析

    2018-2019-2 网络对抗技术 20165317 Exp4 恶意代码分析 实验要求 1.系统运行监控 使用如计划任务,每隔一分钟记录自己的电脑有哪些程序在联网,连接的外部IP是哪里.运行一段时间 ...

  4. 44-0-STM32的CAN外设

    1.RS-485 协议主要是把 RS-232 的信号改进成差分信号,从而大大提高了抗干扰特性: 在 RS-485 通讯网络中,节点中的串口控制器使用 RX 与 TX信号线连接到收发器上,而收发器通过差 ...

  5. readlink 获取进程的绝对路径

    readlink可以获取exe所在的路径(直接和进程关联);无法获得so的路径,so路径可以用dladdr,参考另一篇文章linux系统中有个符号链接:/proc/self/exe 它代表当前程序,所 ...

  6. npm手册

    npm现在都是随同NodeJS一起安装的包管理和分发工具,所以npm的安装,只要下载新版的nodejs已经集成了npm. 安装好了以后,直接输入npm或者npm help,会出来一些npm自带的命令. ...

  7. MyEclipse破解步骤

    1.下载安装(注:安装后不要打开myeclipse,以下步骤完成方可打开) 2.解压破解文件 3.打开文件夹patch 3.全部复制 4.找到myeclipse的安装目录,打开plugins文件夹 5 ...

  8. CDI services--Event(事件)

    Cdi中的event事件,是整个CDI的精华所在之一.其有点类似设计模式中的观察者模式.但也有不同的地方.如下3点: 不仅是生产者(producers)从观察者(observers)解耦.观察者也从生 ...

  9. Mac vs code 快捷键

    control  +  shift  +  L 选中所有匹配的所有单词,光标选中

  10. JS33个概念

        JavaScript开发者应懂的33个概念 简介 这个项目是为了帮助开发者掌握 JavaScript 概念而创立的.它不是必备,但在未来学习(JavaScript)中,可以作为一篇指南. 本篇 ...