c# Word 模版 打印
最近一个项目需要用到C# Word打印,经过几天折腾,终于得到一个颇为完美的方案。
新建一个Word操作类
首先需要添加COM引用-------Microsoft Word 11.0 Object Library
添加命名空间-------------------using Word = Microsoft.Office.Interop.Word;
private static Word._Document wDoc = null; --word文档
private static Word._Application wApp = null; --word进程
开启一个新的word进程
Word.Application thisApplication = new Word.ApplicationClass();
wApp = thisApplication;
string tmpDocFile="D:\Documents and Settings\Administrator\桌面\tmp.doc"
object templatefile = tmpDocFile;
wDoc = wApp.Documents.Add(ref templatefile, ref missing, ref missing, ref missing); //在现有进程内打开文档
wDoc.Activate(); //当前文档置前
------------------------字符替换模块----------------------------------------------------------------------
//替换模版中的字符开始
object replaceAll = Word.WdReplace.wdReplaceAll; //替换所有
wApp.Selection.Find.ClearFormatting();
wApp.Selection.Find.Text = "#old#";
wApp.Selection.Find.Format = false;
wApp.Selection.Find.Forward = true;
wApp.Selection.Find.MatchByte = true;
wApp.Selection.Find.Wrap = Word.WdFindWrap.wdFindAsk;
wApp.Selection.Find.Replacement.ClearFormatting();
wApp.Selection.Find.Replacement.Text = "new string"; //替换后新字符
wApp.Selection.Find.Execute(
//替换模版中的字符开始结束
-------以上模块的作用是查找模版文件中所有的字符"#old#"替换成新字符"new string"
-------如果需要替换不同的字符,循环以上模块即可
-------也可以采用网上说的建立书签那种模式,不过我认为比较麻烦,不大方便,若遇到有大量数据需要替换的模版则麻烦,这个简单
----------------------在指定位置处插入图片 ,或者替换字符为图片-----------------------------------
//一般我们要在模版内插入图片,这个位置是事先定好的,我们在模版内使用字符串“#Image#”来代替
//插入图片结束 , 如果有多个图片需要替换,循环该模块即可
------------------------使用Printout方法进行打印------------------------------
页面发送完毕到打印机后才执行下一步操作
missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing);