2016-08-04 1 views
1

私はドキュメントのヘッダにプレースホルダ「plcDate」を交換したい機能していない、ヘッダのプレースホルダを交換してください。ヘッダーは、私のドキュメントテンプレートの2ページ目から始まります。

私は以下のコードを使用しています。しかし、 'headDate'は常にnullです。

は、私は、コードやドキュメントのテンプレートを変更するためにきたかどうかわかりません。次のコードを使用した後に勤務

using (WordprocessingDocument theDoc = WordprocessingDocument.Open(NewPath, true)) 
{ 
    MainDocumentPart mainPart = theDoc.MainDocumentPart; 
    foreach (HeaderPart hpart in mainPart.HeaderParts) 
    { 
     SdtElement headDate = hpart.Header.Descendants<SdtElement>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "plcDate").SingleOrDefault(); 
     if (headDate != null) 
     { 
      headDate.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Text(dateValue)))); 
     } 
    } 
    mainPart.Document.Save(); 
} 
+0

は、あなたが' headDate'と二度 'headSDate'を持っていたら、というタイプミスでしょうか? – Philippe

+0

申し訳ありません。それはタイプミスです。ありがとう – Ashin

答えて

0

: `foreach`で

using (WordprocessingDocument theDoc = WordprocessingDocument.Open(NewPath, true)) 
       { 
        MainDocumentPart mainPart = theDoc.MainDocumentPart; 
        string content = null; 

        using (StreamReader reader = new StreamReader(theDoc.MainDocumentPart.HeaderParts.First().GetStream())) 
        { 
         content = reader.ReadToEnd(); 
        } 
        Regex exheadDate = new Regex("plcDate"); 
        content = exheadDate.Replace(content, "27/07/1992"); 
        using (StreamWriter writer = new StreamWriter(theDoc.MainDocumentPart.HeaderParts.First().GetStream(FileMode.Create))) 
        { 
         writer.Write(content); 
        } 
        mainPart.Document.Save(); 
       }