Creare una tabella
Aspose.Words consente agli utenti di creare tabelle in un documento da zero e fornisce diversi metodi per farlo. Questo articolo presenta dettagli su come aggiungere tabelle formattate al documento utilizzando ciascun metodo, nonché un confronto di ciascun metodo alla fine dell’articolo.
Stili di tabella predefiniti
Alla tabella appena creata vengono dati valori predefiniti simili a quelli utilizzati in Microsoft Word:
Proprietà Tabella | Predefinito in Aspose.Words |
---|---|
Border Style |
Single |
Border Width |
1/2 pt |
Border Color |
Black |
Left and Right Padding |
5.4 pts |
AutoFit Mode |
AutoFit to Window |
Allow AutoFit |
True |
Creare una tabella con DocumentBuilder
In Aspose.Words, gli utenti possono creare una tabella in un documento utilizzando DocumentBuilder. L’algoritmo di base per la creazione di una tabella è il seguente:
- Inizia la tabella con StartTable
- Aggiungi una cella alla tabella usando InsertCell – questo avvia automaticamente una nuova riga
- Facoltativamente, utilizzare la proprietà CellFormat per specificare la formattazione delle celle
- Inserire il contenuto della cella utilizzando i metodi DocumentBuilder appropriati, ad esempio Writeln, InsertImage e altri
- Ripetere i passaggi 2 -4 fino al completamento della riga
- Chiama EndRow per terminare la riga corrente
- Facoltativamente, utilizzare la proprietà RowFormat per specificare la formattazione delle righe
- Ripetere i passaggi 2 -7 fino al completamento della tabella
- Chiama EndTable per terminare la costruzione della tabella
Dettagli importanti:
- StartTable può anche essere chiamato all’interno di una cella, nel qual caso inizia la creazione di una tabella nidificata all’interno della cella.
- Dopo aver chiamato InsertCell, viene creata una nuova cella e qualsiasi contenuto aggiunto utilizzando altri metodi della classe DocumentBuilder verrà aggiunto alla cella corrente. Per creare una nuova cella sulla stessa riga, chiamare di nuovo InsertCell.
- Se InsertCell viene chiamato immediatamente dopo EndRow e alla fine di una riga, la tabella continuerà su una nuova riga.
- Il metodo EndTable per terminare la tabella deve essere chiamato una sola volta dopo aver chiamato EndRow. La chiamata EndTable sposta il cursore dalla cella corrente alla posizione immediatamente successiva alla tabella.
Il processo di creazione di una tabella può essere chiaramente visto nella seguente immagine:
L’esempio di codice seguente mostra come creare una tabella semplice usando DocumentBuilder con formattazione predefinita:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
// Start building the table. | |
builder->StartTable(); | |
builder->InsertCell(); | |
builder->Write(u"Row 1, Cell 1 Content."); | |
// Build the second cell. | |
builder->InsertCell(); | |
builder->Write(u"Row 1, Cell 2 Content."); | |
// Call the following method to end the row and start a new row. | |
builder->EndRow(); | |
// Build the first cell of the second row. | |
builder->InsertCell(); | |
builder->Write(u"Row 2, Cell 1 Content"); | |
// Build the second cell. | |
builder->InsertCell(); | |
builder->Write(u"Row 2, Cell 2 Content."); | |
builder->EndRow(); | |
// Signal that we have finished building the table. | |
builder->EndTable(); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.CreateSimpleTable.docx"); |
L’esempio di codice seguente mostra come creare una tabella formattata utilizzando DocumentBuilder:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
SharedPtr<Table> table = builder->StartTable(); | |
builder->InsertCell(); | |
// Table wide formatting must be applied after at least one row is present in the table. | |
table->set_LeftIndent(20.0); | |
// Set height and define the height rule for the header row. | |
builder->get_RowFormat()->set_Height(40.0); | |
builder->get_RowFormat()->set_HeightRule(HeightRule::AtLeast); | |
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::FromArgb(198, 217, 241)); | |
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center); | |
builder->get_Font()->set_Size(16); | |
builder->get_Font()->set_Name(u"Arial"); | |
builder->get_Font()->set_Bold(true); | |
builder->get_CellFormat()->set_Width(100.0); | |
builder->Write(u"Header Row,\n Cell 1"); | |
// We don't need to specify this cell's width because it's inherited from the previous cell. | |
builder->InsertCell(); | |
builder->Write(u"Header Row,\n Cell 2"); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(200.0); | |
builder->Write(u"Header Row,\n Cell 3"); | |
builder->EndRow(); | |
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_White()); | |
builder->get_CellFormat()->set_Width(100.0); | |
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center); | |
// Reset height and define a different height rule for table body. | |
builder->get_RowFormat()->set_Height(30.0); | |
builder->get_RowFormat()->set_HeightRule(HeightRule::Auto); | |
builder->InsertCell(); | |
// Reset font formatting. | |
builder->get_Font()->set_Size(12); | |
builder->get_Font()->set_Bold(false); | |
builder->Write(u"Row 1, Cell 1 Content"); | |
builder->InsertCell(); | |
builder->Write(u"Row 1, Cell 2 Content"); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(200.0); | |
builder->Write(u"Row 1, Cell 3 Content"); | |
builder->EndRow(); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(100.0); | |
builder->Write(u"Row 2, Cell 1 Content"); | |
builder->InsertCell(); | |
builder->Write(u"Row 2, Cell 2 Content"); | |
builder->InsertCell(); | |
builder->get_CellFormat()->set_Width(200.0); | |
builder->Write(u"Row 2, Cell 3 Content."); | |
builder->EndRow(); | |
builder->EndTable(); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.FormattedTable.docx"); |
L’esempio di codice seguente mostra come inserire una tabella nidificata usando DocumentBuilder:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
SharedPtr<Cell> cell = builder->InsertCell(); | |
builder->Writeln(u"Outer Table Cell 1"); | |
builder->InsertCell(); | |
builder->Writeln(u"Outer Table Cell 2"); | |
// This call is important to create a nested table within the first table. | |
// Without this call, the cells inserted below will be appended to the outer table. | |
builder->EndTable(); | |
// Move to the first cell of the outer table. | |
builder->MoveTo(cell->get_FirstParagraph()); | |
// Build the inner table. | |
builder->InsertCell(); | |
builder->Writeln(u"Inner Table Cell 1"); | |
builder->InsertCell(); | |
builder->Writeln(u"Inner Table Cell 2"); | |
builder->EndTable(); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.NestedTable.docx"); |
Creare una tabella tramite DOM (Document Object Model)
È possibile inserire tabelle direttamente nel DOM aggiungendo un nuovo nodo Table in una posizione specifica.
Si noti che immediatamente dopo la creazione del nodo della tabella, la tabella stessa sarà completamente vuota, cioè non contiene ancora righe e celle. Per inserire righe e celle in una tabella, aggiungere i nodi figlio Row e Cell appropriati al DOM.
L’esempio di codice seguente mostra come creare una nuova tabella da zero aggiungendo i nodi figlio appropriati all’albero del documento:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(); | |
// We start by creating the table object. Note that we must pass the document object | |
// to the constructor of each node. This is because every node we create must belong | |
// to some document. | |
auto table = MakeObject<Table>(doc); | |
doc->get_FirstSection()->get_Body()->AppendChild(table); | |
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used | |
// to ensure that the specified node is valid. In this case, a valid table should have at least one Row and one cell. | |
// Instead, we will handle creating the row and table ourselves. | |
// This would be the best way to do this if we were creating a table inside an algorithm. | |
auto row = MakeObject<Row>(doc); | |
row->get_RowFormat()->set_AllowBreakAcrossPages(true); | |
table->AppendChild(row); | |
// We can now apply any auto fit settings. | |
table->AutoFit(AutoFitBehavior::FixedColumnWidths); | |
auto cell = MakeObject<Cell>(doc); | |
cell->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightBlue()); | |
cell->get_CellFormat()->set_Width(80); | |
cell->AppendChild(MakeObject<Paragraph>(doc)); | |
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Row 1, Cell 1 Text")); | |
row->AppendChild(cell); | |
// We would then repeat the process for the other cells and rows in the table. | |
// We can also speed things up by cloning existing cells and rows. | |
row->AppendChild(cell->Clone(false)); | |
row->get_LastCell()->AppendChild(MakeObject<Paragraph>(doc)); | |
row->get_LastCell()->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Row 1, Cell 2 Text")); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.InsertTableDirectly.docx"); |
Creare una tabella da HTML
Aspose.Words supporta l’inserimento di contenuto in un documento da un’origine HTML utilizzando il metodo InsertHtml. L’input può essere una pagina HTML completa o solo uno snippet parziale.
Utilizzando il metodo InsertHtml, gli utenti possono inserire tabelle nel documento tramite tag di tabella come <table>
, <tr>
, <td>
.
Il seguente esempio di codice mostra come inserire una tabella in un documento da una stringa contenente tag HTML:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
// Note that AutoFitSettings does not apply to tables inserted from HTML. | |
builder->InsertHtml(String(u"<table>") + u"<tr>" + u"<td>Row 1, Cell 1</td>" + u"<td>Row 1, Cell 2</td>" + u"</tr>" + u"<tr>" + | |
u"<td>Row 2, Cell 2</td>" + u"<td>Row 2, Cell 2</td>" + u"</tr>" + u"</table>"); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.InsertTableFromHtml.docx"); |
Inserire una copia di una tabella esistente
Ci sono spesso momenti in cui è necessario creare una tabella basata su una tabella già esistente in un documento. Il modo più semplice per duplicare una tabella mantenendo tutta la formattazione è clonare il nodo della tabella usando il metodo Clone.
La stessa tecnica può essere utilizzata per aggiungere copie di una riga o cella esistente a una tabella.
L’esempio di codice seguente mostra come duplicare una tabella utilizzando i costruttori di nodi:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Tables.docx"); | |
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true)); | |
// Clone the table and insert it into the document after the original. | |
auto tableClone = System::ExplicitCast<Table>(table->Clone(true)); | |
table->get_ParentNode()->InsertAfter(tableClone, table); | |
// Insert an empty paragraph between the two tables, | |
// or else they will be combined into one upon saving this has to do with document validation. | |
table->get_ParentNode()->InsertAfter(MakeObject<Paragraph>(doc), table); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.CloneCompleteTable.docx"); |
L’esempio di codice seguente mostra come clonare l’ultima riga di una tabella e aggiungerla alla tabella:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git. | |
auto doc = MakeObject<Document>(MyDir + u"Tables.docx"); | |
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true)); | |
auto clonedRow = System::ExplicitCast<Row>(table->get_LastRow()->Clone(true)); | |
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into. | |
for (const auto& cell : System::IterateOver<Cell>(clonedRow->get_Cells())) | |
{ | |
cell->RemoveAllChildren(); | |
} | |
table->AppendChild(clonedRow); | |
doc->Save(ArtifactsDir + u"WorkingWithTables.CloneLastRow.docx"); |
Se stai cercando di creare tabelle in un documento che crescono dinamicamente con ogni record dall’origine dati, il metodo sopra non è consigliato. Invece, l’output desiderato è più facilmente raggiungibile usando Mail merge con le regioni. Puoi saperne di più su questa tecnica nel Mail Merge con Regioni sezione.
Confronta i modi per creare una tabella
Aspose.Words fornisce diversi metodi per creare nuove tabelle in un documento. Ogni metodo ha i suoi vantaggi e svantaggi, quindi la scelta di quale utilizzare spesso dipende dalla situazione specifica.
Diamo un’occhiata più da vicino a questi modi di creare tabelle e confrontiamo i loro pro e contro:
Metodo | Vantaggio | Svantaggio |
---|---|---|
DocumentBuilder |
Il metodo standard per l’inserimento di tabelle e altri contenuti del documento | A volte è difficile creare molte varietà di tabelle contemporaneamente con la stessa istanza builder |
Via DOM | Si adatta meglio al codice circostante che crea e inserisce i nodi direttamente nel DOM senza utilizzare un DocumentBuilder | La tabella viene creata “vuota”: prima di eseguire la maggior parte delle operazioni, è necessario chiamare EnsureMinimum per creare eventuali nodi figlio mancanti |
Da HTML | Può creare una nuova tabella da sorgente HTML utilizzando tag come <table> , <tr> , <td> |
Non tutti i possibili formati di tabella Microsoft Word possono essere applicati all’HTML |
Clonazione di una tabella esistente | È possibile creare una copia di una tabella esistente mantenendo tutta la formattazione di riga e cella | I nodi figlio appropriati devono essere rimossi prima che la tabella sia pronta per l’uso |