替换标题占位符,现在不工作

时间:2016-08-04 07:36:05

标签: c# openxml

我想在doc的标题中替换占位符'plcDate'。标题从我的doc模板中的第2页开始。

我正在使用以下代码。但'headDate'始终为空。

不知道我是否要更改代码或文档模板。

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();
}

1 个答案:

答案 0 :(得分:0)

使用以下代码后工作:

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();
                }