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. [dev][socket] unix domain socket删除socket文件

    问题 在使用unix domain socket的时候,bind之后,会在本地路径里 产生一个与path对应的socket文件. 如何正确的在用完socket之后,对其销毁呢? 方案 使用 unlin ...

  2. 内置函数-max、min、round、sorted、ord、chr、any、all、dir、eval、exec、map、filter、reduce

    http://www.nnzhp.cn/archives/152 1.max,min,round print(max([3,4.563,3,6,2.5])) #取最大值,可循环参数即可,int类型的, ...

  3. python-装饰器实现pv-uv

    python-装饰器实现pv-uv   网站流量统计可以帮助我们分析网站的访问和广告来访等数据,里面包含很多数据的,比如访问试用的系统,浏览器,ip归属地,访问时间,搜索引擎来源,广告效果等.原来是一 ...

  4. 初学node.js,安装nodemon,学习debug模式,安装cpu-stat

    1.运行node  文件     node .\01.js      文件内容   console.log('aaaa'); 2.因为每次更新文件都需要重新,所以安装nodemon    npm i ...

  5. weblogic使用wlst脚本实现自动部署

    创建weblogic的server和cluster ip="10.20.0.2" nwport=8001 wwport=9001 nwlist=[ ('wtdsrwnw','Clu ...

  6. 原生js标识当前导航位置(给当前导航一个className=active)

    导航html结构为: <div class="header2-nav"> <a href="index.html">首页</a&g ...

  7. gitbook build/serve 失败,Error: ENOENT: no such file or directory, stat ...

    我使用的 gitbook 版本 CLI version: 2.3.2 GitBook version: 3.2.3 在使用 gitbook 生成文档时,发现编译偶尔不规律性地出现错误 d:\Mine\ ...

  8. Request的方法和数组

    req.getHeader("referer") [取得发送请求页面对应的浏览器地址栏信息,可以使用这种方法实现防盗链等操作] String name=new String(req ...

  9. C++ 自定义订单号

    自定义订单号 #include<iostream> #include<stack> #include <time.h> #include <sys/timeb ...

  10. 解决Qt下ssl出错的办法

    在使用 QNetworkAccessManager 时出现的ssl错误:qt.network.ssl: QSslSocket: cannot resolve SSL_set_psk_client_ca ...