Vytvoření tabulky

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 představuje podrobnosti o tom, jak přidat formátované tabulky do dokumentu pomocí každé metody, a také srovnání každé metody na konci článku.

Výchozí Styly Tabulky

Nově vytvořená tabulka má výchozí hodnoty podobné těm, které se používají v Microsoft Word:

Vlastnost Tabulky Výchozí hodnota v Aspose.Words
Border Style Single
Border Width 1/2 bod
Border Color Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

Vytvořte tabulku pomocí DocumentBuilder

V Aspose.Words mohou uživatelé vytvořit tabulku v dokumentu pomocí DocumentBuilder. Základní algoritmus pro vytvoření tabulky je následující:

  1. Začněte tabulku StartTable
  2. Přidání buňky do tabulky pomocí InsertCell - tím se automaticky spustí nový řádek
  3. Volitelně použijte vlastnost CellFormat k určení formátování buněk
  4. Vložte obsah buňky pomocí příslušných metod DocumentBuilder, jako je Writeln, InsertImage a dalších
  5. Opakujte kroky 2-4, dokud není řádek dokončen
  6. Volání EndRow pro ukončení aktuálního řádku
  7. Volitelně použijte vlastnost RowFormat k určení formátování řádků
  8. Opakujte kroky 2-7, dokud není tabulka dokončena
  9. Zavolejte EndTable a dokončete sestavení tabulky

Proces vytváření tabulky je jasně vidět na následujícím obrázku:

creating-table-process

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-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");

Následující příklad kódu ukazuje, jak vytvořit formátovanou tabulku pomocí 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");

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-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");
view raw nested-table.h hosted with ❤ by GitHub

Vytvoření tabulky pomocí DOM (model objektu dokumentu)

Tabulky můžete vložit přímo do DOM přidáním nového uzlu Table na konkrétní pozici.

Vezměte prosím na vědomí, že ihned po vytvoření uzlu tabulky bude samotná tabulka zcela prázdná, to znamená, že ještě neobsahuje řádky a buňky. Chcete-li vložit řádky a buňky do tabulky, přidejte příslušné podřízené uzly Row a Cell do DOM.

Následující příklad kódu ukazuje, jak vytvořit novou tabulku od nuly přidáním příslušných podřízených uzlů do stromu dokumentů:

// 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");

Vytvořte tabulku z HTML

Aspose.Words podporuje vkládání obsahu do dokumentu ze zdroje HTML metodou InsertHtml. Vstupem může být úplná stránka HTML nebo jen částečný úryvek.

Pomocí metody InsertHtml mohou uživatelé vkládat tabulky do dokumentu pomocí značek tabulek, jako je <table>, <tr>, <td>.

Následující příklad kódu ukazuje, jak vložit tabulku do dokumentu z řetězce obsahujícího značky 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");

Vložení kopie existující tabulky

Často se stává, že potřebujete vytvořit tabulku na základě již existující tabulky v dokumentu. Nejjednodušší způsob, jak duplikovat tabulku při zachování veškerého formátování, je klonovat uzel tabulky pomocí metody Clone.

Stejnou techniku lze použít k přidání kopií existujícího řádku nebo buňky do tabulky.

Následující příklad kódu ukazuje, jak duplikovat tabulku pomocí konstruktorů uzlů:

// 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");

Následující příklad kódu ukazuje, jak klonovat poslední řádek tabulky a připojit jej k tabulce:

// 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");

Pokud se díváte na vytváření tabulek v dokumentu, které dynamicky rostou s každým záznamem ze zdroje dat, výše uvedená metoda se nedoporučuje. Místo toho je požadovaného výstupu snadněji dosaženo použitím Mail merge s regiony. Více o této technice se můžete dozvědět v Mail Merge s regiony oddíl.

Porovnejte způsoby vytvoření tabulky

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, který se má použít, často závisí na konkrétní situaci.

Podívejme se blíže na tyto způsoby vytváření tabulek a porovnejme jejich klady a zápory:

Způsoba Výhoda Nevýhoda
DocumentBuilder Standardní metoda pro vkládání tabulek a dalšího obsahu dokumentu Někdy je obtížné vytvořit mnoho druhů tabulek současně se stejnou instancí stavitele
Via DOM Lépe zapadá do okolního kódu, 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, abyste vytvořili chybějící podřízené uzly
Od HTML Může vytvořit novou tabulku ze zdroje HTML pomocí značek jako <table>, <tr>, <td> Ne všechny možné formáty tabulek Microsoft Word lze použít na HTML
Klonování existující tabulky Můžete vytvořit kopii existující tabulky při zachování veškerého formátování řádků a buněk Příslušné podřízené uzly musí být odstraněny, než bude tabulka připravena k použití