Sending text to Mail-Merge Fields in Microsoft Word 2010

后端 未结 2 1156
小蘑菇
小蘑菇 2021-01-03 16:08

I\'m using the following code to send a text to a simple word template I\'ve set up just with a single MergeField at present to test I can get this working.
The code I a

2条回答
  •  迷失自我
    2021-01-03 17:05

    The final code I used and which works for me is as follows:

    public static void TextToWord(string pWordDoc, string pMergeField, string pValue)
        {
            Object oMissing = System.Reflection.Missing.Value;
            Object oTrue = true;
            Object oFalse = false;
            Word.Application oWord = new Word.Application();
            Word.Document oWordDoc = new Word.Document();
            oWord.Visible = true;
            Object oTemplatePath = pWordDoc;
            oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
            foreach (Word.Field myMergeField in oWordDoc.Fields)
            {
                Word.Range rngFieldCode = myMergeField.Code;
                String fieldText = rngFieldCode.Text;
                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 == pMergeField)
                    {
                        myMergeField.Select();
                        oWord.Selection.TypeText(pValue);
                    }
                }
            }
        }
    

    This code is orignally from here.

提交回复
热议问题