1

我想创建 Word 模板内的合并字段列表。在询问 goole 后,我找到并使用了该代码:

static void Main(string[] args)
{
    //OBJECT OF MISSING "NULL VALUE"
    Object oMissing = System.Reflection.Missing.Value;
    Object oTemplatePath = "D:\\MyTemplate.dotx";

    Application wordApp = new Application();
    Document wordDoc = new Document();

    wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

    foreach (Field myMergeField in wordDoc.Fields)
    {
        Range rngFieldCode = myMergeField.Code;
        String fieldText = rngFieldCode.Text;

        // ONLY GETTING THE MAILMERGE FIELDS

        if (fieldText.StartsWith(" MERGEFIELD"))
        {
            // THE TEXT COMES IN THE FORMAT OF
            // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
            // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

            Int32 endMerge = fieldText.IndexOf("\\");
            Int32 fieldNameLength = fieldText.Length - endMerge;

            String fieldName = fieldText.Substring(11, endMerge - 11);
            // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

            fieldName = fieldName.Trim();

            // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
            // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE

            if (fieldName == "Name")
            {
                myMergeField.Select();
                wordApp.Selection.TypeText("Vivek");
            }
        }
    }
    wordDoc.SaveAs("myfile.doc");
    wordApp.Documents.Open("myFile.doc");
    wordApp.Application.Quit();
}

当模板包含 <> 合并字段时,这项工作,但当合并字段在文本框内时,我不起作用。你能告诉我如何扫描整个文档吗?还是文本框?

4

0 回答 0