Vytvořit tabulku
Aspose.Words umožňuje uživatelům vytvářet tabulky v dokumentu od nuly a poskytuje několik různých metod. Tento článek uvádí podrobnosti o tom, jak přidat formátované tabulky do dokumentu pomocí každé metody, stejně jako srovnání každé metody na konci článku.
Výchozí styl tabulky
Nově vytvořená tabulka je dána výchozími hodnotami podobnými hodnotám používaným v Microsoft Word:
Tabulka Vlastnosti | Výchozí v 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 |
Vytvořit tabulku s dokumentemBuilder
In Aspose.Words, uživatelé mohou vytvořit tabulku v dokumentu pomocí DocumentBuilder. Základní algoritmus pro vytvoření tabulky je následující:
- Spustit tabulku s StartTable
- Přidání buňky do tabulky pomocí InsertCell Toto automaticky spustí nový řádek
- Volitelně použijte CellFormat vlastnost pro upřesnění formátování buněk
- Vložit obsah buňky pomocí příslušného DocumentBuilder metody, jako jsou Writeln, InsertImage, a další
- Opakujte kroky 2-4, dokud není řada dokončena
- Volat EndRow ukončit aktuální řádek
- Volitelně použijte RowFormat vlastnost pro upřesnění formátování řádku
- Opakujte kroky 2-7 až do dokončení tabulky
- Volat EndTable dokončit stavbu stolu
Důležité informace:
- StartTable lze také volat uvnitř buňky, v takovém případě to začne vytvořením vnořeného stolu uvnitř buňky.
- Po zavolání InsertCell, vytvoří se nová buňka a jakýkoliv obsah, který přidáte pomocí jiných metod DocumentBuilder třída bude přidána do současné buňky. Chcete-li vytvořit novou buňku ve stejné řadě, zavolejte InsertCell Znovu.
- Pokud InsertCell volá okamžitě po EndRow a konec řady, tabulka bude pokračovat v nové řadě.
- • EndTable způsob ukončení tabulky by měl být volán pouze jednou po volání EndRow. Volání EndTable přesune kurzor z aktuální buňky do polohy bezprostředně po tabulce.
Proces vytváření tabulky lze jasně vidět na následujícím obrázku:
Následující příklad kódu ukazuje, jak vytvořit jednoduchou tabulku pomocí DocumentBuilder s výchozím formátováním:
// 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"); |
Následující příklad kódu ukazuje, jak vytvořit formátovanou tabulku pomocí nástroje DokumentBuilder:
// 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"); |
Následující příklad kódu ukazuje, jak vložit vnořenou tabulku pomocí 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"); |
Vytvořit tabulku prostřednictvím DOM (Document Object Model)
Tabulky můžete vložit přímo do DOM přidáním nového Table Uzel na konkrétní pozici.
Vezměte prosím na vědomí, že ihned po vytvoření uzel stolu bude tabulka sama o sobě zcela prázdná, tj. dosud neobsahuje řádky a buňky. Pro vložení řádků a buněk do tabulky přidejte odpovídající Row a Cell dětské uzly na DOM.
Následující příklad kódu ukazuje, jak postavit novou tabulku od nuly přidáním odpovídajících dětských uzlů do stromu dokumentu:
// 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"); |
Vytvořit tabulku z HTML
Aspose.Words podporuje vložení obsahu do dokumentu ze zdroje HTML pomocí InsertHtml metoda. Vstup může být kompletní HTML stránka nebo jen částečný úryvek.
Použití InsertHtml způsob, uživatelé mohou vložit tabulky do dokumentu pomocí tagy tabulky jako <table>
, <tr>
, <td>
.
Následující příklad kódu ukazuje, jak vložit tabulku do dokumentu z řetězce obsahující HTML tagy:
// 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"); |
Vložit kopii existující tabulky
Často jsou chvíle, kdy potřebujete vytvořit tabulku založenou na již existující tabulce v dokumentu. Nejjednodušší způsob, jak duplikovat tabulku a zároveň zachovat formátování, je klonovat uzel tabulky pomocí Clone metoda.
Stejnou techniku lze použít pro přidání kopií existující řady nebo buňky do tabulky.
Následující příklad kódu ukazuje, jak duplikovat tabulku pomocí konstruktérů nódu:
// 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"); |
Následující příklad kódu ukazuje, jak naklonovat poslední řádek tabulky a přidat ji do tabulky:
// 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"); |
Pokud se díváte na vytváření tabulek v dokumentu, který dynamicky roste s každým záznamem z vašeho datového zdroje, pak výše uvedená metoda se nedoporučuje. Místo toho je žádoucí výstup snadněji dosaženo použitím Mail merge s regiony. O této technice se můžete dozvědět více v Mail Merge s regiony sekce.
Porovnat způsoby, jak vytvořit tabulku
Aspose.Words poskytuje několik metod pro vytvoření nových tabulek v dokumentu. Každá metoda má své vlastní výhody a nevýhody, takže výběr z nich často závisí na konkrétní situaci.
Pojďme se blíže podívat na tyto způsoby vytváření tabulek a porovnat jejich výhody a nevýhody:
Metoda | Výhody | Nevýhody |
---|---|---|
Via DocumentBuilder |
Standardní metoda pro vložení tabulek a jiného obsahu dokumentu | Někdy je obtížné vytvořit mnoho druhů tabulek současně se stejnými stavebníky |
Via DOM | Sedí lépe s okolním kódem, který vytváří a vkládá uzly přímo do DOM bez použití DocumentBuilder | Tabulka je vytvořena “prázdná”: před provedením většiny operací musíte zavolat EnsureMinimum vytvořit chybějící dětské uzly |
Od HTML | Lze vytvořit novou tabulku ze zdroje HTML pomocí značek jako <table> , <tr> , <td> |
Ne všechny možné Microsoft Word formáty tabulky lze aplikovat na HTML |
Klonování stávající tabulky | Můžete vytvořit kopii existující tabulky a zároveň zachovat formátování všech řádků a buněk | Příslušné dětské uzly musí být odstraněny dříve, než je tabulka připravena k použití |