Aspose.Words如何在Word中快速创建指定行数和列数的表格

作者:控件中国网   出处:控件中国网   2016-09-01 11:14:28   阅读:15

Aspose.Words是一款强大的Word文档编辑控件,几乎可以实现Microsoft Words软件可以实现的所有功能,在Word中经常需要插入各种表格,Aspose.Words也可以使用代码轻松插入表格,并且对表格样式进行各种设置,控件提供了InsertRow和InsertCell方法专门用于表格的创建,只是当表格行数与列数比较多时,使用上面的函数逐一创建的话就相当繁琐了,根据很多客户的需求,希望Aspose.Words在指定行数和列数的情况下直接创建表格,下面的代码就描述了如何直接使用列数和行数创建表格:
Document doc = new Document();
Table outerTable = CreateTable(doc, 5, 10, "Cell's text");
// Add it to the document body.
doc.FirstSection.Body.AppendChild(outerTable);
 
doc.Save(MyDir + "Out v16.7.0.docx");
/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private static Table CreateTable(Document doc, int rowCount, int cellCount, string cellText)
{
    Table table = new Table(doc);
 
    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);
 
        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));
 
            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }
 
    return table;
}
Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat