[英]Open XML document unreadable after adding footer
I am trying to add footer in a word document by using the below code. 我试图通过使用以下代码在Word文档中添加页脚。 The file is getting generated, but when I try to open the file it is showing the message that the document is unreadable. 该文件正在生成,但是当我尝试打开该文件时,它显示该文档不可读的消息。 I don't know what I am doing wrong here. 我不知道我在做什么错。
WordprocessingDocument doc;
Body docBody;
public void Insert()
{
doc = WordprocessingDocument.Create(@"d:\report1.docx", WordprocessingDocumentType.Document);
docBody = new Body();
MainDocumentPart mainPart = doc.AddMainDocumentPart();
mainPart.Document = new Document();
mainPart.Document.Body = docBody;
ApplyFooter();
doc.Save();
}
public void ApplyFooter()
{
// Get the main document part.
MainDocumentPart mainDocPart = doc.MainDocumentPart;
FooterPart footerPart1 = mainDocPart.AddNewPart<FooterPart>("r98");
Footer footer1 = new Footer();
Paragraph paragraph1 = new Paragraph() { };
Run run1 = new Run();
Text text1 = new Text();
text1.Text = "Footer stuff";
run1.Append(text1);
paragraph1.Append(run1);
footer1.Append(paragraph1);
footerPart1.Footer = footer1;
SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants<SectionProperties>().FirstOrDefault();
if (sectionProperties1 == null)
{
sectionProperties1 = new SectionProperties() { };
mainDocPart.Document.Body.Append(sectionProperties1);
}
FooterReference footerReference1 = new FooterReference() { Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = "r98" };
sectionProperties1.InsertAt(footerReference1, 0);
}
You need to call doc.Close();
您需要调用doc.Close();
at the end of your Insert
method. 在您的Insert
方法的末尾。 That will save and close any underlying streams. 这将保存并关闭所有基础流。 You can remove the call to doc.Save()
. 您可以删除对doc.Save()
的调用。
It's possibly cleaner to use a using
statement which will call Close
for you: 使用using
语句为您调用Close
可能更干净:
WordprocessingDocument doc;
Body docBody;
public void Insert()
{
using (doc = WordprocessingDocument.Create(@"d:\report1.docx", WordprocessingDocumentType.Document))
{
Body docBody = new Body();
MainDocumentPart mainPart = doc.AddMainDocumentPart();
mainPart.Document = new Document();
mainPart.Document.Body = docBody;
ApplyFooter();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.