Creează o Tabelă

Aspose.Words permite utilizatorilor să creeze tabele în documente din start și oferă mai multe metode diferite pentru a face acest lucru. Acest articol prezintă detalii despre cum să adăugați tabele formatate în documentul dumneavoastră folosind fiecare metodă, precum și o comparație a fiecărei metode la sfârșitul articolului.

Stiluri tabele implicite

Tabelul proaspăt creat este dat valori implicite similare cu cele utilizate în Microsoft Word:

Proprietatea Tabelului Default la 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

Creează o Tabelă cu DocumentBuilder

În Aspose.Words, utilizatorii pot crea o masă într-un document folosind DocumentBuilder. Algoritmul de bază pentru crearea unei tabele este ca acesta:

  1. Începe tabelul cu StartTable
  2. Adăugați o celulă la tabel folosind InsertCell – aceasta va începe automat un nou rând
  3. În mod opțional, utilizați proprietatea CellFormat pentru a specifica formatarea celulei
  4. Introduce conținutul celulei folosind metodele DocumentBuilder potrivite, cum ar fi Writeln, InsertImage și altele
  5. Repetă pașii 2-4 până când rândul este complet
  6. Apelați EndRow pentru a încheia rândul curent
  7. În mod opțional, utilizați proprietatea RowFormat pentru a specifica formatarea rândului
  8. Repetă pașii 2-7 până când tabelul este complet
  9. Sună EndTable să termeni de construit masa

Procesul de creare a unei tabele poate fi văzut clar în imaginea următoare:

creating-table-process

Exemplul următor de cod arată cum să creezi o simplă tabelă folosind DocumentBuilder cu formatare implicită:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Start building the table.
builder.StartTable();
builder.InsertCell();
builder.Write("Row 1, Cell 1 Content.");
// Build the second cell.
builder.InsertCell();
builder.Write("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("Row 2, Cell 1 Content");
// Build the second cell.
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content.");
builder.EndRow();
// Signal that we have finished building the table.
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx");

Exemplul următor de cod arată cum se creează o masă formatată folosind DocumentBuilder:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
builder.InsertCell();
// Table wide formatting must be applied after at least one row is present in the table.
table.LeftIndent = 20.0;
// Set height and define the height rule for the header row.
builder.RowFormat.Height = 40.0;
builder.RowFormat.HeightRule = HeightRule.AtLeast;
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Size = 16;
builder.Font.Name = "Arial";
builder.Font.Bold = true;
builder.CellFormat.Width = 100.0;
builder.Write("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("Header Row,\n Cell 2");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Header Row,\n Cell 3");
builder.EndRow();
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
builder.CellFormat.Width = 100.0;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
// Reset height and define a different height rule for table body.
builder.RowFormat.Height = 30.0;
builder.RowFormat.HeightRule = HeightRule.Auto;
builder.InsertCell();
// Reset font formatting.
builder.Font.Size = 12;
builder.Font.Bold = false;
builder.Write("Row 1, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 1, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 1, Cell 3 Content");
builder.EndRow();
builder.InsertCell();
builder.CellFormat.Width = 100.0;
builder.Write("Row 2, Cell 1 Content");
builder.InsertCell();
builder.Write("Row 2, Cell 2 Content");
builder.InsertCell();
builder.CellFormat.Width = 200.0;
builder.Write("Row 2, Cell 3 Content.");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx");

Exemplul următor de cod arată cum să inserezi o masă încastrată folosind DocumentBuilder:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Cell cell = builder.InsertCell();
builder.Writeln("Outer Table Cell 1");
builder.InsertCell();
builder.Writeln("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.FirstParagraph);
// Build the inner table.
builder.InsertCell();
builder.Writeln("Inner Table Cell 1");
builder.InsertCell();
builder.Writeln("Inner Table Cell 2");
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx");
view raw nested-table.cs hosted with ❤ by GitHub

Creează o tabelă via DOM (Document Object Model)

Puteți insera tabele direct în DOM adăugând un nod Table nou la o poziție specifică.

Vă rugăm să rețineți că imediat după crearea nodului de tabel, tabelul însuși va fi complet gol, adică nu conține încă rânduri și celule. Pentru a insera rânduri și celule într-o tabelă, adăugați nodurile corespunzătoare Row și Cell ca copii ale DOM.

Exemplul de cod de mai jos arată cum să construiți o nouă tabelă din cămașă prin adăugarea nodurilor corespunzătoare copilului la arborele de documente:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new 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.
Table table = new Table(doc);
doc.FirstSection.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.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "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.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));
// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx");

Crează o tabele de la HTML

Aspose.Words acceptă inserarea conținutului într-un document dintr-o sursă HTML folosind metoda InsertHtml. Intrarea poate fi o pagină HTML completă sau doar un fragment parțial.

Utilizând metoda InsertHtml, utilizatorii pot introduce tabele în document folosind etichete de tip tabel ca <table>, <tr>, <td>.

Exemplul următor de cod arată cum să introducem o 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-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Note that AutoFitSettings does not apply to tables inserted from HTML.
builder.InsertHtml("<table>" +
"<tr>" +
"<td>Row 1, Cell 1</td>" +
"<td>Row 1, Cell 2</td>" +
"</tr>" +
"<tr>" +
"<td>Row 2, Cell 2</td>" +
"<td>Row 2, Cell 2</td>" +
"</tr>" +
"</table>");
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx");

Înserare a unei Copii de o Tabelă Existenta

Sunt adesea momente când trebuie să creezi o tabelă bazată pe o altă tabelă deja existentă într-un document. Cea mai ușoară metodă de a duplica o tabelă în timp ce se păstrează formatarea este să clonezi nodul “Tabel” folosind metoda Clone.

Același tehnic poate fi folosit pentru a adăuga copii ale unei rânduri existente sau celule într-o tabelă.

Exemplul de cod următor arată cum se poate duplica o tabelă folosind constructorii de noduri:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
// Clone the table and insert it into the document after the original.
Table tableClone = (Table) table.Clone(true);
table.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.ParentNode.InsertAfter(new Paragraph(doc), table);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx");

Exemplul de cod următor arată cum se clonează ultima rând dintr-o tabelă și se atașează la tabelă:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Row clonedRow = (Row) table.LastRow.Clone(true);
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
foreach (Cell cell in clonedRow.Cells)
cell.RemoveAllChildren();
table.AppendChild(clonedRow);
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx");

Dacă ești în căutarea creării tabelelor într-un document care cresc dinamic cu fiecare înregistrare din sursa de date, atunci metoda de mai sus nu este recomandată. În schimb, ieșirea dorită este mai ușor realizată folosind Mail merge cu regiuni. Puteţi afla mai multe despre această tehnică în secțiunea Mail Merge with Regions.

Comparați modurile de a crea un tabel

Aspose.Words oferă mai multe metode de creare a unor tabele noi într-un document. Fiecare metodă are avantajele şi dezavantajele ei, aşa că alegerea celei care urmează să fie folosită depinde adesea de situaţia specifică.

Să aruncăm o privire mai atentă la aceste moduri de a crea tabele și să comparăm avantajele și dezavantajele acestora:

Metoda Avantaje Dezavantajele
Via DocumentBuilder Metoda standard pentru inserarea tabelelor și a altor conținuturi de documente Uneori e greu să creezi multe tipuri de tabele în același timp cu aceeași instanță de constructor
Via DOM Se potrivește mai bine cu codul înconjurătoare care creează și inserează noduri direct în DOM, fără a folosi un DocumentBuilder Tabelul este creat “goale”: înainte de a efectua majoritatea operațiilor, trebuie să apelați EnsureMinimum pentru a crea orice noduri copil lipsă
De la HTML Poate crea o nouă tabelă din sursa HTML folosind etichete ca <table>, <tr>, <td> Nu toate formate de masă Microsoft Word posibile pot fi aplicate la HTML
Clonarea unei tabele existente Puteți crea o copie a unei tabele existente păstrând toate formatările de rând și celulă Copiii potriviți trebuie să fie eliminați înainte de ca tabelul să fie gata pentru utilizare