使用Open XML将数据表导出到带有页码的Word文档中

问题描述 投票:0回答:1

我的要求是:将动态数据表导出到具有页码的Word文档我们需要使用Open XML来实现这一点。我有将Datatable导出到Word的代码。并插入页码。

我获得了以下代码以导出数据表

public void CreateWordtable(string filename,DataTable data)
{
    WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
    MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
    mainDocPart.Document = new Document();
    Body body = new Body();
    mainDocPart.Document.Append(body);
    //rinks@::creating new table

    DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();            
    for (int i = 0; i < data.Rows.Count; ++i)
    {
        TableRow row = new TableRow();
        for (int j = 0; j < data.Columns.Count; j++)
        {
            TableCell cell = new TableCell();
            cell.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
            cell.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1200" }));
            row.Append(cell);
        }
        table.Append(row);
    }
    body.Append(table);
    doc.MainDocumentPart.Document.Save();
    doc.Dispose();
}

下面的代码是在Word文档中插入页码

private static void AddPageNumberFooters(WordprocessingDocument parent)
{
    string documentPath = @"D:\EmptyDoc.docx";
    using (WordprocessingDocument package =
        WordprocessingDocument.Open(documentPath, true))
    {
        var mainDocumentPart = parent.AddMainDocumentPart();
        GenerateMainDocumentPart().Save(mainDocumentPart);

        var documentSettingsPart =
            mainDocumentPart.AddNewPart
            <DocumentSettingsPart>("rId1");

        GenerateDocumentSettingsPart().Save(documentSettingsPart);

        var firstPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId1");
        GeneratePageFooterPart("Page 1 of 2").Save(firstPageFooterPart);

        var secondPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId2");
        GeneratePageFooterPart("Page 2 of 2").Save(secondPageFooterPart);
    }
}


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 SectionProperties(
                    new FooterReference()
                    {
                        Type = HeaderFooterValues.First,
                        Id = "rId1"
                    },
                    new FooterReference()
                    {
                        Type = HeaderFooterValues.Even,
                        Id = "rId2"
                    },
                    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 Header GeneratePageHeaderPart(string HeaderText)
{
    var element =
        new Header(
            new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId() { Val = "Header" }),
                new Run(
                    new Text(HeaderText))
            ));

    return element;
}

我的问题是,我结合了以上两种方法来导出数据和页码。如果我们知道单词文档中有2页,我可以插入2个FooterParts。但是我不知道导出数据后将创建多少个页面。

c# asp.net-mvc-4 openxml
1个回答
0
投票

尝试以下代码来自动添加页码:

  private static string GenerateFooterPartContent(WordprocessingDocument package, string text = null)
    {
        FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
        if (footerPart1 == null)
        {
            footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
        }

        var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
        // Get SectionProperties and set HeaderReference and FooterRefernce with new Id
        SectionProperties sectionProperties1 = new SectionProperties();
        FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
        sectionProperties1.Append(footerReference2);
        package.MainDocumentPart.Document.Body.Append(sectionProperties1);


        Footer footer1 = new Footer();

        var r = new Run();
        PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right, 
            RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin, 
            Leader = AbsolutePositionTabLeaderCharValues.None };

        r.Append(positionalTab2);
        paragraph2.Append(r);

        r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the page number dynamically ***
              new SimpleField() { Instruction = "PAGE" },
              new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the number of pages dynamically ***
              new SimpleField() { Instruction = "NUMPAGES" });
        paragraph2.Append(r);

        footer1.Append(paragraph2);

        footerPart1.Footer = footer1;
        return relationshipId;
    }
© www.soinside.com 2019 - 2024. All rights reserved.