简体   繁体   中英

Open XML document unreadable after adding footer

I am trying to add footer in a word document by using the below code. 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(); at the end of your Insert method. That will save and close any underlying streams. You can remove the call to doc.Save() .

It's possibly cleaner to use a using statement which will call Close for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM