Creați un tabel
Aspose.Words permite utilizatorilor să creeze tabele într-un document de la zero și oferă mai multe metode diferite pentru a face acest lucru. Acest articol prezintă detalii despre cum să adăugați tabele formatate la documentul dvs. utilizând Fiecare metodă, precum și o comparație a fiecărei metode la sfârșitul articolului.
Stiluri De Masă Implicite
Tabelului nou creat i se dau valori implicite similare cu cele utilizate în Microsoft Word:
Proprietatea Tabelului | Implicit în 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 |
Creați un tabel cu DocumentBuilder
În Aspose.Words, Utilizatorii pot crea un tabel într-un document folosind DocumentBuilder. Algoritmul de bază pentru crearea unui tabel este următorul:
- Începeți tabelul cu StartTable
- Adăugați o celulă la tabel folosind InsertCell - aceasta pornește automat un nou rând
- Opțional, utilizați proprietatea CellFormat pentru a specifica formatarea celulei
- Introduceți conținutul celulei folosind metodele corespunzătoare DocumentBuilder, cum ar fi Writeln, InsertImage și altele
- Repetați pașii 2 - 4 până când rândul este complet
- Apelați EndRow pentru a încheia rândul curent
- Opțional, utilizați proprietatea RowFormat pentru a specifica formatarea rândurilor
- Repetați pașii 2 - 7 până când tabelul este complet
- Apelați EndTable pentru a termina construirea mesei
Detalii importante:
- StartTable poate fi, de asemenea, numit în interiorul unei celule, caz în care începe crearea unui tabel imbricat în interiorul celulei.
- După apelarea InsertCell, se creează o nouă celulă și orice conținut pe care îl adăugați folosind alte metode din clasa DocumentBuilder va fi adăugat la celula curentă. Pentru a crea o celulă nouă pe același rând, apelați din nou InsertCell.
- Dacă InsertCell este apelat imediat după EndRow și sfârșitul unui rând, tabelul va continua pe un rând nou.
- Metoda EndTable pentru a încheia tabelul trebuie apelată o singură dată după apelarea EndRow. Apelarea EndTable mută cursorul din celula curentă în poziția imediat după tabel.
Procesul de creare a unui tabel poate fi văzut clar în imaginea următoare:
Următorul exemplu de cod arată cum să creați un tabel simplu folosind DocumentBuilder cu formatare implicită:
// 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"); |
Următorul exemplu de cod arată cum se creează un tabel formatat folosind 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"); |
Următorul exemplu de cod arată cum să inserați un tabel imbricat folosind 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"); |
Creați un tabel prin DOM (Document Object Model)
Puteți insera tabele direct în DOM adăugând un nou nod Table la o anumită poziție.
Vă rugăm să rețineți că imediat după crearea nodului tabelului, tabelul în sine va fi complet gol, adică nu conține încă rânduri și celule. Pentru a insera rânduri și celule într-un tabel, adăugați nodurile copil corespunzătoare Row și Cell la DOM.
Următorul exemplu de cod arată cum să construiți un nou tabel de la zero prin adăugarea nodurilor copil corespunzătoare în arborele de documente:
// 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"); |
Creați un tabel din HTML
Aspose.Words acceptă inserarea conținutului într-un document dintr-o sursă HTML folosind metoda InsertHtml. Intrarea poate fi o pagină completă HTML sau doar un fragment parțial.
Folosind metoda InsertHtml, utilizatorii pot insera tabele în document prin etichete de tabel precum <table>
, <tr>
, <td>
.
Următorul exemplu de cod arată cum să inserați un tabel într-un document dintr-un șir care conține etichete 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"); |
Inserați o copie a unui tabel existent
Există adesea momente când trebuie să creați un tabel bazat pe un tabel deja existent într-un document. Cel mai simplu mod de a duplica un tabel păstrând în același timp toate formatările este de a clona nodul tabelului folosind metoda Clone.
Aceeași tehnică poate fi utilizată pentru a adăuga copii ale unui rând sau celulă existentă la un tabel.
Următorul exemplu de cod arată cum să duplicați un tabel folosind constructori de noduri:
// 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"); |
Următorul exemplu de cod arată cum să clonați ultimul rând al unui tabel și să îl adăugați la tabel:
// 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"); |
Dacă vă uitați la crearea de tabele într-un document care cresc dinamic cu fiecare înregistrare din sursa de date, atunci metoda de mai sus nu este recomandată. În schimb, rezultatul dorit este mai ușor de obținut prin utilizarea Mail merge cu regiuni. Puteți afla mai multe despre această tehnică în Mail Merge cu regiuni secțiunea.
Comparați modalitățile de a crea un tabel
Aspose.Words oferă mai multe metode pentru a crea tabele noi într-un document. Fiecare metodă are propriile avantaje și dezavantaje, astfel încât alegerea utilizării depinde adesea de situația specifică.
Să aruncăm o privire mai atentă asupra acestor moduri de a crea tabele și de a compara avantajele și dezavantajele acestora:
Metoda | Avantaje | Dezavantaje |
---|---|---|
DocumentBuilder |
Metoda standard pentru inserarea tabelelor și a altor conținuturi ale documentelor | Uneori dificil de a crea mai multe soiuri de tabele, în același timp, cu aceeași instanță constructor |
Prin DOM | Se potrivește mai bine cu codul înconjurător care creează și inserează noduri direct în DOM fără a utiliza un DocumentBuilder | Tabelul este creat “gol”: înainte de a efectua majoritatea operațiunilor, trebuie să apelați EnsureMinimum pentru a crea noduri copil lipsă |
Din HTML | Poate crea un nou tabel din HTML sursă folosind etichete precum <table> , <tr> , <td> |
Nu toate formatele de tabel Microsoft Word posibile pot fi aplicate la HTML |
Clonarea unui tabel existent | Puteți crea o copie a unui tabel existent păstrând în același timp toate formatarea rândurilor și celulelor | Nodurile copil corespunzătoare trebuie eliminate înainte ca tabelul să fie gata de utilizare |