We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Fill a table from .net objects

Tried to load data from list of object type into a ODT document, but couldn’t find a suitable way of filling the data. I know there are mainly 3 ways to create / insert data into a word table with Aspose:

  • using DocumenBuilder (a “facade” of Document structure -> faster approach that abstracts the complexity of DOM);
  • using DOM;
  • fill from Datatable

I’ve used the first, using Document builder. To simplify: we have a class Person. Create a list of type and use it to fill table.
From the approach seen on: https://apireference.aspose.com/words/net/aspose.words.tables/table/constructors/main

    foreach (var person in persons)
                {
                    Row row = new Row(doc);
                    table.AppendChild(row);
                    for (int cellId = 1; cellId <= totCols; cellId++)
                    {
                        Cell cell = new Cell(doc);
                        cell.AppendChild(new Paragraph(doc));
                        cell.FirstParagraph.AppendChild(new Run(doc, persons[cellId].Name));
                        row.AppendChild(cell);
                    }
                }

Now here is filling the table only with Name property.
We would have several properties eg: Age, DOB, Address, Gender.

How do we fill the table with all the properties (each column will be a property)
How do we fill the table with only some properties (eg. Name, Age and DOB)

Doesn’t have to be necessarily the same mechanism (through Document bulider). Just what is the simplest, more efficient and performance wise way of filling the table from a class ?

@Remus87,
You can use the DocumentBuilder methods to generate a table with desired contents. Please check the following code example:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();
foreach (var person in persons)
{
    Cell currentCell = builder.InsertCell();
    currentCell.FirstParagraph.AppendChild(new Run(doc, person.Name));

    currentCell = builder.InsertCell();
    currentCell.FirstParagraph.AppendChild(new Run(doc, person.Age));

    currentCell = builder.InsertCell();
    currentCell.FirstParagraph.AppendChild(new Run(doc, person.DOB));

    currentCell = builder.InsertCell();
    currentCell.FirstParagraph.AppendChild(new Run(doc, person.Address));

    currentCell = builder.InsertCell();
    currentCell.FirstParagraph.AppendChild(new Run(doc, person.Gender));

    builder.EndRow();
}
builder.EndTable();

doc.Save("testTable.docx");