How to Build a Table from a DataTable
Often your application will pull data from a database and store it in the form of a DataTable. You may wish to easily insert this data into your document as a new table and quickly apply formatting to the whole table.
Using Aspose.Words this task is very simple to achieve. The code presented in this article demonstrates how to do this.
To build a table in a document from the data found in a DataTable:
- Create a new DocumentBuilder object on your Document.
- Start a new table using DocumentBuilder.
- If we want to insert the names of each of the columns from our DataTable as a header row then iterate through each data column and write the column names into a row in the table.
- Iterate through each DataRow in the DataTable.
- Iterate through each object in the DataRow.
- Insert the object into the document using DocumentBuilder. The method used depends on the type of the object being inserted e.g DocumentBuilder.writeln() for text and DocumentBuilder.insertImage() for a byte array which represents an image.
- At the end of processing of the data row also end the row being created by the [DocumentBuilder]https://reference.aspose.com/words/java/com.aspose.words/DocumentBuilder) by using DocumentBuilder.endRow().
- Once all rows from the DataTable have been processed finish the table by calling DocumentBuilder.endTable().
- Finally, we can set the desired table style using one of the appropriate table properties such as Table.getStyleIdentifier() to automatically apply formatting to the entire table. The following data in our DataTable is used in this example:
The following code demonstrates how to achieve this in Aspose.Words. The ImportTableFromDataTable method accepts a DocumentBuilder object, the DataTable containing the data and a flag which specifies if the column heading from the DataTable are included at the top of the table. This method builds a table from these parameters using the builder’s current position and formatting.
The following code example provides a method to import data from the DataTable and insert it into a new table using the DocumentBuilder.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/* | |
* Imports the content from the specified DataTable into a new Aspose.Words | |
* Table object. The table is inserted at the current position of the | |
* document builder and using the current builder's formatting if any is | |
* defined. | |
*/ | |
public static Table importTableFromDataTable(DocumentBuilder builder, DataTable dataTable, boolean importColumnHeadings) throws Exception { | |
Table table = builder.startTable(); | |
ResultSetMetaData metaData = dataTable.getResultSet().getMetaData(); | |
int numColumns = metaData.getColumnCount(); | |
// Check if the names of the columns from the data source are to be included in a header row. | |
if (importColumnHeadings) { | |
// Store the original values of these properties before changing them. | |
boolean boldValue = builder.getFont().getBold(); | |
int paragraphAlignmentValue = builder.getParagraphFormat().getAlignment(); | |
// Format the heading row with the appropriate properties. | |
builder.getFont().setBold(true); | |
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); | |
// Create a new row and insert the name of each column into the first row of the table. | |
for (int i = 1; i < numColumns + 1; i++) { | |
builder.insertCell(); | |
builder.writeln(metaData.getColumnName(i)); | |
} | |
builder.endRow(); | |
// Restore the original formatting. | |
builder.getFont().setBold(boldValue); | |
builder.getParagraphFormat().setAlignment(paragraphAlignmentValue); | |
} | |
// Iterate through all rows and then columns of the data. | |
while (dataTable.getResultSet().next()) { | |
for (int i = 1; i < numColumns + 1; i++) { | |
// Insert a new cell for each object. | |
builder.insertCell(); | |
// Retrieve the current record. | |
Object item = dataTable.getResultSet().getObject(metaData.getColumnName(i)); | |
// This is name of the data type. | |
String typeName = item.getClass().getSimpleName(); | |
if (typeName.equals("byte[]")) { | |
// Assume a byte array is an image. Other data types can be added here. | |
builder.insertImage((byte[]) item, 50, 50); | |
} else if (typeName.equals("Timestamp")) { | |
// Define a custom format for dates and times. | |
builder.write(new SimpleDateFormat("MMMM d, yyyy").format((Timestamp) item)); | |
} else { | |
// By default any other item will be inserted as text. | |
builder.write(item.toString()); | |
} | |
} | |
// After we insert all the data from the current record we can end the table row. | |
builder.endRow(); | |
} | |
// We have finished inserting all the data from the DataTable, we can end the table. | |
builder.endTable(); | |
return table; | |
} |
The method can then be easily called using your DocumentBuilder and data.
The following code example shows how to import the data from a DataTable and insert it into a new table in the document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Create a new document. | |
Document doc = new Document(); | |
// We can position where we want the table to be inserted and also specify any extra formatting to be | |
// applied onto the table as well. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// We want to rotate the page landscape as we expect a wide table. | |
doc.getFirstSection().getPageSetup().setOrientation(Orientation.LANDSCAPE); | |
// Retrieve the data from our data source which is stored as a DataTable. | |
DataTable dataTable = null; //getEmployees(databaseDir); | |
// Build a table in the document from the data contained in the DataTable. | |
Table table = importTableFromDataTable(builder, dataTable, true); | |
// We can apply a table style as a very quick way to apply formatting to the entire table. | |
table.setStyleIdentifier(StyleIdentifier.MEDIUM_LIST_2_ACCENT_1); | |
table.setStyleOptions(TableStyleOptions.FIRST_ROW | TableStyleOptions.ROW_BANDS | TableStyleOptions.LAST_COLUMN); | |
// For our table we want to remove the heading for the image column. | |
table.getFirstRow().getLastCell().removeAllChildren(); | |
doc.save(dataDir + "Table.FromDataTable_Out.docx"); |
The following table is produced by running the code above: