微软Word办公自动化 - 填写文本表单字段和复选框表单字段和邮件合并(MS Word Office

2019-07-04 13:35发布

有没有人对如何使用C#创建一个引擎的任何好的建议或经验(VB.NET是好的,太)是通用的,足以应付微软Word文本字段的大多数情况下,我需要填写的数据,我从数据库中获取? 总之,我即将踏上这个小办公自动化漂移,我希望这里的反馈一点点可以帮助我避免一些耗费时间的错误。

干杯,感谢您的任何意见;

戴夫

Answer 1:

我会派两个例子来解决你的自动化问题。 第一种是使用邮件合并和第二使用的书签。

Word文件看起来是这样的:

使用邮件合并(插入 - >快速零件 - >字段 - >邮件合并 - >合并域)的名字:«的firstName»姓:«lastName的»

=======

使用书签(插入 - >收藏)的名字:(< - 书签就在这里,它是不可见)姓:

并且代码如下:

  1. 使用书签

      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!"); 
  2. 使用邮件合并

      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 missing, ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

        oDoc.Activate();
    }

    public void SaveAs(string strFileName)
    {
        object missing = System.Reflection.Missing.Value;
        object fileName = strFileName;

        oDoc.SaveAs(ref fileName, 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);
    }

    public void Quit()
    {
        object missing = System.Reflection.Missing.Value;
        oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
    }

我希望这个实施会给一些想法解决您的问题。



文章来源: MS Word Office Automation - Filling Text Form Fields And Check Box Form Fields And Mail Merge