簡體   English   中英

添加頁腳后無法打開XML文檔

[英]Open XML document unreadable after adding footer

我試圖通過使用以下代碼在Word文檔中添加頁腳。 該文件正在生成,但是當我嘗試打開該文件時,它顯示該文檔不可讀的消息。 我不知道我在做什么錯。

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

    }

在此處輸入圖片說明

您需要調用doc.Close(); 在您的Insert方法的末尾。 這將保存並關閉所有基礎流。 您可以刪除對doc.Save()的調用。

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM