有些时候我们需要通过word模板来打印,需要将数据库查询出来的数据填充到word模板文档并批量打印,此时我们可以在word模板设置好书签,然后通过在程序里面通过书签定位填充数据,然后再生成新的文档并且打印。
string fileName = “test.docx”;
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("团号", "12321");
dic.Add("线路简称", “线路23”);
dic.Add("所属社", “南京旅游社”);
dic.Add("当前日期", DateTime.Now.ToString("yyyy年MM月dd日"));
ReplaceContentByRemarks(fileName, dic);
/// <summary>
/// 替换指定书签的内容
/// </summary>
/// <param name="wordApp">当前打开的MSWord.ApplicationClass对象</param>
/// <param name="doc">当前打开的word文档,类型为MSWord._Document</param>
/// <param name="bookMarkName">书签名</param>
/// <param name="newValue">新值</param>
/// <returns></returns>
public static bool ReplaceContentByRemarks(MSWord.ApplicationClass wordApp,MSWord._Document doc,object bookMarkName,string newValue)
{
/*
* 如果需要删除某个书签内容,只需要使用空格字符串替换就行(string.empty替换不行,可以使用" ")
*
*/
try
{
if (doc.Bookmarks.Exists(bookMarkName.ToString()))//如果书签存在
{
doc.Bookmarks[bookMarkName].Range.Select();//选中书签文本
doc.ActiveWindow.Selection.TypeText(newValue);
return true;
}
return false;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 替换指定书签的内容
/// </summary>
/// <param name="docObject">word文档名(全路径)</param>
/// <param name="dic">存储键值对,键是书签名,值为替换后的新内容</param>
public static void ReplaceContentByRemarks(object docObject, Dictionary<string, string> dic)
{
MSWord.ApplicationClass wordApp = new MSWord.ApplicationClass();
wordApp.Visible = false;
object Nothing = System.Reflection.Missing.Value;
MSWord._Document doc = null;
object isVisible = false;
try
{
doc = wordApp.Documents.Open(ref docObject, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing,
ref Nothing, ref Nothing, ref Nothing);
/*
* 循环替换每个书签内容
*
*/
foreach (KeyValuePair<string,string> item in dic)
{
ReplaceContentByRemarks(wordApp,doc,item.Key,item.Value);
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (doc != null)
{
doc.Close();
}
if (wordApp != null)
{
wordApp.Quit();
wordApp = null;
}
}
}