在VS中使用C#,我试图根据日期更改word文档标题中的跟踪更改中的作者姓名。使用调试器,似乎作者的名字正在改变,但文档更改没有得到保存。我已经包含了'headerPart.Header.Save()'行,这可能是一招,但没有运气。在更改完成后我需要帮助保存文档 - 谢谢!
private void changeRevAuthor(string docPath, string input_project_date)
{
using (Stream stream = System.IO.File.Open(docPath, FileMode.OpenOrCreate))
{
stream.Seek(0, SeekOrigin.End);
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true))
{
foreach (HeaderPart headerPart in document.MainDocumentPart.HeaderParts)
{
foreach (OpenXmlElement headerElement in headerPart.RootElement.Descendants())
{
OpenXmlElement children = headerPart.RootElement;
XElement xchildren = XElement.Parse(children.OuterXml);
var ychildren = xchildren.Descendants().Where(x => x.Attributes(w + "author").Count() > 0);
foreach (XElement descendant in ychildren)
{
var date = descendant.Attribute(w + "date").ToString().Substring(8, 10);
if (DateTime.Parse(date) > DateTime.Parse(input_project_date))
{
descendant.SetAttributeValue(w + "author", "new author name");
Debug.WriteLine("this is the new one" + descendant);
}
}
}
headerPart.Header.Save();
Debug.WriteLine("We got here");
}
document.Close();
}
}
}
答案 0 :(得分:0)
使用MainDocumentPart
save()方法保存文档中的更改。
即:document.MainDocumentPart.Document.Save();