C# MS Word Office 自动化 - 填写文本表单域和复选框表单域以及邮件合并

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1371093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:46:55  来源:igfitidea点击:

MS Word Office Automation - Filling Text Form Fields And Check Box Form Fields And Mail Merge

c#vb.netms-wordms-office

提问by Daver

Does anyone have any good advice or experience on how to create an engine using C# (VB.NET is okay too) that is generic enough to handle most cases of MS Word text fields I need to fill with data I'm getting from a database? In short, I'm about to embark on this little Office automation excursion and I'm hoping a little bit of feedback here may help me to avoid some time consuming errors.

有没有人有关于如何使用 C#(VB.NET 也可以)创建引擎的任何好的建议或经验,该引擎足够通用以处理大多数情况下的 MS Word 文本字段我需要填充我从数据库中获取的数据? 简而言之,我即将开始这个小小的 Office 自动化之旅,我希望这里的一些反馈可以帮助我避免一些耗时的错误。

Cheers and thanks in advance for any advice;

提前干杯并感谢您的任何建议;

Dave

戴夫

采纳答案by ZokiManas

I will sent two examples for solving your automation problem. The first one is using MailMerge and the second is using bookmarks.

我将发送两个示例来解决您的自动化问题。第一个是使用 MailMerge,第二个是使用书签。

The word file looks like this:

word文件如下所示:

Using MailMerge (Insert - > Quick Parts -> Field -> Mail merge -> Merge field) First name: ?firstName? Last name: ?lastName?

使用 MailMerge(插入 -> 快速部件 -> 字段 -> 邮件合并 -> 合并字段) 名字:?firstName? 姓氏:?姓氏?

=======

========

Using Bookmarks( Insert -> BookMark) First name: (<- the bookmark is here, it's not visible) Last name:

使用书签(插入 -> 书签)名字:(<- 书签在这里,它不可见)姓氏:

And the code is following:

代码如下:

  1. Using bookmarks

        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. Using 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!");
    
  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!");
    

I've also used some helper methods.

我还使用了一些辅助方法。

    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);
    }

I hope that this implementation will give some ideas for solving your problem.

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