C#读写Word⽂件(五)--替换
有些时候我们需要通过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) {
/*
* 如果需要删除某个书签内容,只需要使⽤空格字符串替换就⾏(pty替换不⾏,可以使⽤" ")
*
*/
try
{
if (doc.Bookmarks.Exists(bookMarkName.ToString()))//如果书签存在
param name{
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;
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论