Costruire una tabella da un DataTable
Spesso l’applicazione estrae i dati da un database e li memorizza sotto forma di DataTable. È possibile inserire facilmente questi dati nel documento come nuova tabella e applicare rapidamente la formattazione all’intera tabella.
Utilizzando Aspose.Words, è possibile recuperare facilmente i dati da un database e memorizzarli come tabella:
- Crea un nuovo oggetto DocumentBuilder sul tuo Document.
- Inizia una nuova tabella usando DocumentBuilder.
- Se vogliamo inserire i nomi di ciascuna delle colonne dal nostro DataTable come riga di intestazione, scorrere ciascuna colonna di dati e scrivere i nomi delle colonne in una riga nella tabella.
- Scorrere ogni DataRow nel DataTable:
- Scorrere ogni oggetto nel DataRow.
- Inserire l’oggetto nel documento usando DocumentBuilder. Il metodo utilizzato dipende dal tipo di oggetto inserito, ad esempio DocumentBuilder.writeln() per il testo e DocumentBuilder.insertImage() per un array di byte che rappresenta un’immagine.
- Al termine dell’elaborazione della riga di dati termina anche la riga creata da DocumentBuilder utilizzando DocumentBuilder.endRow().
- Una volta che tutte le righe di DataTable sono state elaborate, termina la tabella chiamando DocumentBuilder.endTable().
- Infine, possiamo impostare lo stile di tabella desiderato utilizzando una delle proprietà della tabella appropriate come Table.getStyleIdentifier() per applicare automaticamente la formattazione all’intera tabella. In questo esempio vengono utilizzati i seguenti dati nel nostro DataTable:
Il seguente esempio di codice mostra come eseguire l’algoritmo di cui sopra in Aspose.Words:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
/// <summary> | |
/// Imports the content from the specified DataTable into a new Aspose.Words Table object. | |
/// The table is inserted at the document builder's current position and using the current builder's formatting if any is defined. | |
/// </summary> | |
public Table importTableFromDataTable(DocumentBuilder builder, DataTable dataTable, | |
boolean importColumnHeadings) | |
{ | |
Table table = builder.startTable(); | |
// Check if the columns' names 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 (DataColumn column : dataTable.getColumns()) | |
{ | |
builder.insertCell(); | |
builder.writeln(column.getColumnName()); | |
} | |
builder.endRow(); | |
// Restore the original formatting. | |
builder.getFont().setBold(boldValue); | |
builder.getParagraphFormat().setAlignment(paragraphAlignmentValue); | |
} | |
for (DataRow dataRow : (Iterable<DataRow>) dataTable.getRows()) | |
{ | |
for (Object item : dataRow.getItemArray()) | |
{ | |
// Insert a new cell for each object. | |
builder.insertCell(); | |
switch (item.getClass().getName()) | |
{ | |
case "DateTime": | |
// Define a custom format for dates and times. | |
Date dateTime = (Date) item; | |
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM d, yyyy"); | |
builder.write(simpleDateFormat.format(dateTime)); | |
break; | |
default: | |
// By default any other item will be inserted as text. | |
builder.write(item.toString()); | |
break; | |
} | |
} | |
// 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; | |
} |
Il metodo può quindi essere facilmente chiamato usando DocumentBuilder e data.
L’esempio di codice seguente mostra come importare i dati da un DataTable
e inserirli in una nuova tabella nel documento:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git. | |
Document doc = new Document(); | |
// We can position where we want the table to be inserted and specify any extra formatting to the table. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// We want to rotate the page landscape as we expect a wide table. | |
doc.getFirstSection().getPageSetup().setOrientation(Orientation.LANDSCAPE); | |
DataSet ds = new DataSet(); | |
ds.readXml(getMyDir() + "List of people.xml"); | |
// Retrieve the data from our data source, which is stored as a DataTable. | |
DataTable dataTable = ds.getTables().get(0); | |
// 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(getArtifactsDir() + "WorkingWithTables.BuildTableFromDataTable.docx"); |
La tabella mostrata nell’immagine qui sotto è prodotta eseguendo il codice sopra.