word模板导出的几种方式:第一种:占位符替换模板导出(只适用于word中含有表格形式的)
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中含有表格形式的)的更多相关文章
- 关于.net导出数据到excel/word【占位符替换】
1]excel的占位符替换 效果如图 关键代码: ///savedFilePath需要保存的路径 templateDocPath模板路径 替换的关键字和值 格式 [姓名]$%$小王 public st ...
- Android提交数据到服务器的两种方式四种方法
本帖最后由 yanghe123 于 2012-6-7 09:58 编辑 Android应用开发中,会经常要提交数据到服务器和从服务器得到数据,本文主要是给出了利用http协议采用HttpClient方 ...
- 数据库时间内接受的是lang类型的时间 分为三种字段 第一种只存日期 第二种存日期+时间 第三种时间戳
数据库时间内接受的是lang类型的时间 分为三种字段 第一种只存日期 第二种存日期+时间 第三种时间戳
- C# 利用占位符替换word中的字符串和添加图片
利用占位符替换word中的字符串和添加图片 ///<summary> /// 替换word模板文件内容,包括表格中内容 /// 调用如下:WordStr ...
- word模板导出的几种方式:第二种:C#通过模板导出Word(文字,表格,图片) 占位符替换
原文出处:https://www.cnblogs.com/ilefei/p/3508463.html 一:模板的创建 (注意文件后缀只能是.docx或.doct) 在需要位置 插入-文档部件-域, ...
- 创建对象的一种方式&一种继承机制(代码实例)
/* 创建对象的一种方式:混合的构造函数/原型方式, *用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法) */ function People(sname){ this.nam ...
- vue组件通信的几种方式
最近用vue开发项目,记录一下vue组件间通信几种方式 第一种,父子组件通信 一.父组件向子组件传值 1.创建子组件,在src/components/文件夹下新建一个Child.vue 2.Child ...
- 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是一个分布式大数据处理引擎,可以对有限数据流(如离线数据)和无限流数据及逆行有状态计算(不太懂).可以部署在各种集群环境,对各种 ...
- spring配置属性的两种方式
spring配置属性有两种方式,第一种方式通过context命名空间中的property-placeholder标签 <context:property-placeholder location ...
随机推荐
- APP偏移地址
配合BootLoader的APP程序 SCB->VTOR = 0x0803C004; 这里最后还要加上4的原因是 向量表的复位向量地址是4 0地址存的是栈顶
- 如何追踪产生大量REDO的来源
从10点到12点数据库中对象块变化排名靠前的对象 select to_char(begin_interval_time,'YYYY_MM_DD HH24:MI') snap_time, dhsso.o ...
- java 各种数据类型的互相转换
StringBuilder转化为String StringBuilder stb = new StringBuilder(); String str=stb.toString(); //方法1 Str ...
- DateTimeFormat
中文:星期一,星期二 System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.Da ...
- 利用dladdr来获得so自身的路径
#include <dlfcn.h> //定义该函数为了dladdr获取符号信息 void fun1() { } Dl_info info; //dladdr获取某个地址的符号信息 int ...
- vi命令设置行号
1. :set nu :显示行号
- 【LeetCode每天一题】Add Binary(二进制加法)
Given two binary strings, return their sum (also a binary string).The input strings are both non-emp ...
- office word memo
显示左侧目录树 office 和 wps 的差异 wps 的版本:视窗 ->文档结构图 office 的版本: 视图 ->导航窗格
- 安装rosetta2016时出现git@172.16.25.11s password: \r\nPermission denied错误,解决方法。
当在source目录执行 ./external/scons-local/scons.py -j8 mode=release bin 时,报错 git@.11s password: \r\nPermis ...
- 框架的一些bug问题记录
关于java后台生成的mis表,在添加的add页面和edit页面中无法显示,去控制台里面查看.会有些错误的信息,是由于,你的那些html的标签不正常.导致无法显示. 里面有一个高级搜索,可以对这个选择 ...