将标题添加到OpenXML文档

时间:2017-11-03 13:28:31

标签: c# asp.net openxml

我正在以asp.net webform的形式工作,完成后用户需要下载一个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();
}

1 个答案:

答案 0 :(得分:1)

Ludovic Perrichon (http://www.ludovicperrichon.com/) helped me find an answer for this one. While we didn't get my code to work the code here
https://msdn.microsoft.com/en-us/library/ee355228(v=office.12).aspx
does work and allows me to generate a header with the new document.

Slightly modified from the link above:

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;
}
相关问题