2012-11-28 64 views
1

我有一個docx Word文檔,其中包含綁定到CustomXMLPart中的數據的內容控件。使用INCLUDETEXT字段訪問包含文檔的CustomXMLPart

然後通過使用INCLUDETEXT將此文檔(或其中的書籤)包含在另一個Word文檔中。

當第一個文檔被包含到第二個是有什麼辦法從原始文檔中獲取CustomXMLPart(我已經有一個VSTO Word Addin在Word中查看文檔)?

我想要做的就是將它與已存在於第二個文檔中的CustomXMLParts合併,以便內容控件仍然綁定到XMLPart中的數據。

另外,是否有另一種方法來做到這一點,而不使用INCLUDETEXT領域?

回答

1

我認爲這可能是不可能的使用VSTO和IncludeText字段和調查使用altChunk作爲替代。

在打開它之前,我已經使用Open XML SDK 2對文件進行了一些處理,因此可能需要額外的工作才能將文檔合併在一起。

儘管使用altChunk方法在第一個文檔(包括它自己的CustomXmlParts)中嵌入了整個第二個文檔,但CustomXmlParts在文檔打開時被Word丟棄,第二個文檔與第一個文檔合併。

我結束了代碼類似於以下內容。它用altChunk數據替換定義的內容控件,並將特定的CustomXmlParts合併在一起。

private static void CreateAltChunksInWordDocument(WordprocessingDocument doc, string externalDocumentPath) 
    { 
     foreach (var control in doc.ContentControls().ToList()) //Have to do .ToList() on this as when we update the Doc in the loop it stops enumerating otherwise 
     { 
      SdtProperties props = control.Elements<SdtProperties>().FirstOrDefault(); 
      if (props == null) 
       continue; 

      SdtAlias alias = props.Elements<SdtAlias>().FirstOrDefault(); 
      if (alias == null || !alias.Val.HasValue || alias.Val.Value != "External Template") 
       continue; 

      using (WordprocessingDocument externaldoc = WordprocessingDocument.Open(externalDocumentPath, false)) 
      { 
       //Replace the Content Control with an AltChunk section, and stream in the external file 
       string altChunkId = "AltChunkId" + Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", ""); 

       AlternativeFormatImportPart chunk = doc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId); 
       chunk.FeedData(File.OpenRead(externalDocumentPath)); 

       AltChunk altChunk = new AltChunk(); 
       altChunk.Id = altChunkId; 

       OpenXmlElement parent = control.Parent; 
       parent.InsertAfter(altChunk, control); 
       control.Remove(); 

       XDocument xDocMain; 
       CustomXmlPart partMain = MyCommon.GetMyXmlPart(doc.MainDocumentPart, out xDocMain); 

       XDocument xDocExternal; 
       CustomXmlPart partExternal = MyCommon.GetMyXmlPart(externaldoc.MainDocumentPart, out xDocExternal); 

       if (xDocMain != null && partMain != null && xDocExternal != null && partExternal != null) 
       { 
        MyCommon.MergeXmlPartFields(xDocMain, xDocExternal); 

        //Save the updated part 
        using (Stream outputStream = partMain.GetStream()) 
        { 
         using (StreamWriter ts = new StreamWriter(outputStream)) 
         { 
          ts.Write(xDocMain.ToString()); 
         } 
        } 
       } 
      } 
     } 
    } 
相關問題