2014-01-28 32 views
0

我有一個用C#編寫的WinForms應用程序,我使用以下代碼打開Word模板並將數據從SQL數據庫導出到郵件合併字段語言模板。Winforms將數據導出到MS Word合併字段中看不到字段中的字段

try 
{ 
    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 = templatePath;     
    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(); 

      foreach(DataRow r in mergeFields.Rows) 
      { 
       if (r["MergeField"].ToString() == fieldName) 
       { 
        string value = r["Value"].ToString(); 
        myMergeField.Select(); 
        oWord.Selection.TypeText(value); 
       } 
      } 
     } 
    } 
    string fileDetails = caseFolder + "\\" + fileName + @".doc"; 
    oWordDoc.SaveAs2(fileDetails); 
    return fileDetails; 
} 
catch (Exception eX) 
{ 
    throw new Exception("Document: CreateDocument()" + Environment.NewLine + eX.Message); 
} 

這工作正常。但是,我給出的最新模板在文檔標題中包含合併字段並嵌入到文本框中。我的代碼在迭代合併字段時,在標題或文本框中看不到合併字段,但只能看到Word模板主體中的合併字段。

我的問題是,我該如何修改我的代碼以便還可以訪問標題和文本框中的合併字段?

+0

您必須在Word中查找不同故事範圍中的字段,您可以在文檔中使用您知道的特定故事範圍,也可以遍歷所有故事範圍。後者的算法在http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm處提供,但如果您搜索[ms-word]故事範圍的stackoverflow,則可能會找到其他示例。 – 2014-01-30 08:01:18

回答

1

頁眉和頁腳處於分離的XML文件中。您可以解壓縮docx文件以區分差異。 因此,您不僅可以搜索文檔,還可以查找HeaderParts和FooterParts。

我創建了一個example在模板的標題中包含一個合併域。