有没有人有任何关于如何使用C#(VB.NET也可以)创建引擎的任何良好的建议或经验,这是通用的,足以处理大多数情况下MS Word文本字段我需要填充从数据库中获取的数据?简而言之,我即将开始这个小型Office自动化游览,我希望有一点反馈可以帮助我避免一些耗时的错误.
欢迎并提前感谢任何建议;
戴夫
解决方法
我将发送两个解决您的自动化问题的例子.第一个是使用MailMerge,第二个是使用书签.
word文件如下所示:
使用MailMerge(插入 – > Quick Parts – >字段 – >邮件合并 – >合并字段)
名字:«名字»
姓氏:«姓»
=======
使用书签(Insert – > BookMark)
名字:(< - 书签在这里,不可见)
姓:
代码如下:
>使用书签
Open("D:/Doc1.doc"); if (oDoc.Bookmarks.Exists("bkmFirstName")) { object oBookMark = "bkmFirstName"; oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox1.Text; } if (oDoc.Bookmarks.Exists("bkmLastName")) { object oBookMark = "bkmLastName"; oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = textBox2.Text; } SaveAs("D:/Test/Doc2.doc"); Quit(); MessageBox.Show("The file is successfully saved!");
>使用MailMerge
Open("D:/Doc1.doc"); foreach (Field myMergeField in oDoc.Fields) { //iTotalFields++; Range rngFieldCode = myMergeField.Code; String fieldText = rngFieldCode.Text; // GET only MAILMERGE fields if (fieldText.StartsWith(" MERGEFIELD")) { Int32 endMerge = fieldText.IndexOf("\\"); Int32 fieldNameLength = fieldText.Length - endMerge; String fieldName = fieldText.Substring(11,endMerge - 11); fieldName = fieldName.Trim(); if (fieldName == "firstName") { myMergeField.Select(); oWordApplic.Selection.TypeText("This Text Replaces the Field in the Template"); } } } SaveAs("D:/Test/Doc2.doc"); Quit(); MessageBox.Show("The file is successfully saved!");
我也使用了一些帮助方法.
ApplicationClass oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass(); private Microsoft.Office.Interop.Word.Document oDoc = new Document(); public void Open(string strFileName) { object fileName = strFileName; object readOnly = false; object isVisible = true; object missing = System.Reflection.Missing.Value; oDoc = oWordApplic.Documents.Open(ref fileName,ref missing,ref readOnly,ref isVisible,ref missing); oDoc.Activate(); } public void SaveAs(string strFileName) { object missing = System.Reflection.Missing.Value; object fileName = strFileName; oDoc.SaveAs(ref fileName,ref missing); } public void Quit() { object missing = System.Reflection.Missing.Value; oWordApplic.Application.Quit(ref missing,ref missing); }
我希望这个实施将为解决你的问题提供一些想法.