在word文档中创建mergefiels列表

时间:2014-10-23 05:54:30

标签: c# textbox ms-word interop mergefield

我想创建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();
}

当Template包含<>时,这项工作合并域,当合并域在文本框内时我不工作。你能告诉我如何扫描整个文件吗?或文本框呢?

0 个答案:

没有答案