【问题标题】:Add Header to OpenXML Document将标题添加到 OpenXML 文档
【发布时间】:2017-11-03 13:28:30
【问题描述】:

我正在开发 asp.net 网络表单,完成后用户需要下载一个 word 文档,该文档将总结他们选择的答案。我已经成功地将 html 保存为 .doc,但现在客户想要 .docx。我已经能够成功地生成一个他们可以下载的文档,但是对于我来说,我无法显示标题。

似乎有点不对劲的是,如果我使用 Open SML 生产力工具,我在 word 中创建的文档将具有 /word/header1.xml 2 和 3 个标签,我的文档将只有 /word/header.xml .但我不知道如何改变它。

这是我一直在使用的所有代码:

public static void CreateWordprocessingDocument(string filepath)
{
    // Create a document by supplying the filepath. 
    using (WordprocessingDocument wordDocument =
        WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
    {
        // Add a main document part. 
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
        AddSettingsToMainDocumentPart(mainPart);

        // Create the document structure and add some text.
        mainPart.Document = new Document();

        HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>("rId7");
        GenerateHeader(headerPart);

        Body body = mainPart.Document.AppendChild(new Body());
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text("Testing text"));
    }
}

private static void GenerateHeader(HeaderPart part)
{
    Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 w15 w16se wp14" } };
    header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
    header1.AddNamespaceDeclaration("cx", "http://schemas.microsoft.com/office/drawing/2014/chartex");
    header1.AddNamespaceDeclaration("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex");
    header1.AddNamespaceDeclaration("cx2", "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex");
    header1.AddNamespaceDeclaration("cx3", "http://schemas.microsoft.com/office/drawing/2016/5/9/chartex");
    header1.AddNamespaceDeclaration("cx4", "http://schemas.microsoft.com/office/drawing/2016/5/10/chartex");
    header1.AddNamespaceDeclaration("cx5", "http://schemas.microsoft.com/office/drawing/2016/5/11/chartex");
    header1.AddNamespaceDeclaration("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex");
    header1.AddNamespaceDeclaration("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex");
    header1.AddNamespaceDeclaration("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex");
    header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
    header1.AddNamespaceDeclaration("aink", "http://schemas.microsoft.com/office/drawing/2016/ink");
    header1.AddNamespaceDeclaration("am3d", "http://schemas.microsoft.com/office/drawing/2017/model3d");
    header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
    header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
    header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
    header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
    header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
    header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
    header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
    header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
    header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
    header1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
    header1.AddNamespaceDeclaration("w16se", "http://schemas.microsoft.com/office/word/2015/wordml/symex");
    header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
    header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
    header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
    header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

    Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00B22010", RsidRunAdditionDefault = "00B22010" };

    ParagraphProperties paragraphProperties1 = new ParagraphProperties();
    ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };

    paragraphProperties1.Append(paragraphStyleId1);

    Run run1 = new Run();
    Text text1 = new Text() { Space = SpaceProcessingModeValues.Preserve };
    text1.Text = "This is a ";

    run1.Append(text1);

    Run run2 = new Run();
    Text text2 = new Text();
    text2.Text = "header";

    run2.Append(text2);
    BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
    BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };

    paragraph1.Append(paragraphProperties1);
    paragraph1.Append(run1);
    paragraph1.Append(run2);
    paragraph1.Append(bookmarkStart1);
    paragraph1.Append(bookmarkEnd1);

    header1.Append(paragraph1);
    part.Header = header1;
}

private static void AddSettingsToMainDocumentPart(MainDocumentPart part)
{
    DocumentSettingsPart settingsPart = part.AddNewPart<DocumentSettingsPart>();
    settingsPart.Settings = new Settings(
       new Compatibility(
           new CompatibilitySetting()
           {
               Name = new EnumValue<CompatSettingNameValues>(CompatSettingNameValues.CompatibilityMode),
               Val = new StringValue("16"),
               Uri = new StringValue("http://schemas.microsoft.com/office/word")
           }
       )
    );
    settingsPart.Settings.Save();
}

【问题讨论】:

    标签: c# asp.net openxml


    【解决方案1】:

    Ludovic Perrichon (http://www.ludovicperrichon.com/) 帮我找到了这个问题的答案。虽然我们没有让我的代码在这里运行代码
    https://msdn.microsoft.com/en-us/library/ee355228(v=office.12).aspx
    确实有效,并允许我使用新文档生成标题。

    根据上面的链接稍作修改:

    public static void CreateWordprocessingDocument(string filepath)
    {
        string documentPath = filepath;
    
        using (WordprocessingDocument package =
            WordprocessingDocument.Create(
            documentPath, WordprocessingDocumentType.Document))
        {
            AddParts(package);
        }
    }
    
    private static void AddParts(WordprocessingDocument parent)
    {
        var mainDocumentPart = parent.AddMainDocumentPart();
    
        GenerateMainDocumentPart().Save(mainDocumentPart);
    
        var documentSettingsPart =
            mainDocumentPart.AddNewPart
            <DocumentSettingsPart>("rId1");
    
        GenerateDocumentSettingsPart().Save(documentSettingsPart);
    
        var firstPageHeaderPart =
            mainDocumentPart.AddNewPart<HeaderPart>("rId2");
    
        GeneratePageHeaderPart(
            "First page header").Save(firstPageHeaderPart);
    
        var firstPageFooterPart =
            mainDocumentPart.AddNewPart<FooterPart>("rId3");
    
        GeneratePageFooterPart(
            "First page footer").Save(firstPageFooterPart);
    
        var evenPageHeaderPart =
            mainDocumentPart.AddNewPart<HeaderPart>("rId4");
    
        GeneratePageHeaderPart(
            "Even page header").Save(evenPageHeaderPart);
    
        var evenPageFooterPart =
            mainDocumentPart.AddNewPart<FooterPart>("rId5");
    
        GeneratePageFooterPart(
            "Even page footer").Save(evenPageFooterPart);
    
        var oddPageheaderPart =
            mainDocumentPart.AddNewPart<HeaderPart>("rId6");
    
        GeneratePageHeaderPart(
            "Odd page header").Save(oddPageheaderPart);
    
        var oddPageFooterPart =
            mainDocumentPart.AddNewPart<FooterPart>("rId7");
    
        GeneratePageFooterPart(
            "Odd page footer").Save(oddPageFooterPart);
    }
    
    private static Document GenerateMainDocumentPart()
    {
        var element =
            new Document(
                new Body(
                    new Paragraph(
                        new Run(
                            new Text("Page 1 content"))
                    ),
                    new Paragraph(
                        new Run(
                            new Break() { Type = BreakValues.Page })
                    ),
                    new Paragraph(
                        new Run(
                            new LastRenderedPageBreak(),
                            new Text("Page 2 content"))
                    ),
                    new Paragraph(
                        new Run(
                            new Break() { Type = BreakValues.Page })
                    ),
                    new Paragraph(
                        new Run(
                            new LastRenderedPageBreak(),
                            new Text("Page 3 content"))
                    ),
                    new Paragraph(
                        new Run(
                            new Break() { Type = BreakValues.Page })
                    ),
                    new Paragraph(
                        new Run(
                            new LastRenderedPageBreak(),
                            new Text("Page 4 content"))
                    ),
                    new Paragraph(
                        new Run(
                            new Break() { Type = BreakValues.Page })
                    ),
                    new Paragraph(
                        new Run(
                            new LastRenderedPageBreak(),
                            new Text("Page 5 content"))
                    ),
                    new SectionProperties(
                        new HeaderReference()
                        {
                            Type = HeaderFooterValues.First,
                            Id = "rId2"
                        },
                        new FooterReference()
                        {
                            Type = HeaderFooterValues.First,
                            Id = "rId3"
                        },
                        new HeaderReference()
                        {
                            Type = HeaderFooterValues.Even,
                            Id = "rId4"
                        },
                        new FooterReference()
                        {
                            Type = HeaderFooterValues.Even,
                            Id = "rId5"
                        },
                        new HeaderReference()
                        {
                            Type = HeaderFooterValues.Default,
                            Id = "rId6"
                        },
                        new FooterReference()
                        {
                            Type = HeaderFooterValues.Default,
                            Id = "rId7"
                        },
                        new PageMargin()
                        {
                            Top = 1440,
                            Right = (UInt32Value)1440UL,
                            Bottom = 1440,
                            Left = (UInt32Value)1440UL,
                            Header = (UInt32Value)720UL,
                            Footer = (UInt32Value)720UL,
                            Gutter = (UInt32Value)0UL
                        },
                        new TitlePage()
                    )));
    
        return element;
    }
    
    private static Footer GeneratePageFooterPart(string FooterText)
    {
        var element =
            new Footer(
                new Paragraph(
                    new ParagraphProperties(
                        new ParagraphStyleId() { Val = "Footer" }),
                    new Run(
                        new Text(FooterText))
                ));
    
        return element;
    }
    
    private static Header GeneratePageHeaderPart(string HeaderText)
    {
        var element =
            new Header(
                new Paragraph(
                    new ParagraphProperties(
                        new ParagraphStyleId() { Val = "Header" }),
                    new Run(
                        new Text(HeaderText))
                ));
    
        return element;
    }
    
    private static Settings GenerateDocumentSettingsPart()
    {
        var element =
            new Settings(new EvenAndOddHeaders());
    
        return element;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多