Práce se sloupci a řádky

Chcete-li získat větší kontrolu nad tím, jak tabulky fungují, přečtěte si, jak manipulovat se sloupci a řádky.

Najděte Index prvku tabulky

Sloupce, řádky a buňky jsou spravovány přístupem k vybranému uzlu dokumentu podle jeho indexu. Nalezení indexu libovolného uzlu zahrnuje shromáždění všech podřízených uzlů typu prvku z nadřazeného uzlu a poté pomocí metody IndexOf vyhledejte index požadovaného uzlu v kolekci.

Vyhledání indexu tabulky v dokumentu

Někdy možná budete muset provést změny v konkrétní tabulce v dokumentu. Chcete-li to provést, můžete odkazovat na tabulku podle jejího indexu.

Následující příklad kódu ukazuje, jak načíst index tabulky v dokumentu:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
SharedPtr<NodeCollection> allTables = doc->GetChildNodes(NodeType::Table, true);
int tableIndex = allTables->IndexOf(table);

Najděte Index řádku v tabulce

Podobně možná budete muset provést změny v konkrétním řádku ve vybrané tabulce. Chcete-li to provést, můžete také odkazovat na řádek podle jeho indexu.

Následující příklad kódu ukazuje, jak načíst index řádku v tabulce:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
int rowIndex = table->IndexOf(table->get_LastRow());

Najděte Index buňky v řádku

Nakonec možná budete muset provést změny v konkrétní buňce a můžete to provést také indexem buněk.

Následující příklad kódu ukazuje, jak načíst index buňky v řádku:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
int cellIndex = row->IndexOf(row->get_Cells()->idx_get(4));

Práce se sloupci

V modelu objektu Aspose.Words dokumentu (DOM) se uzel Table skládá z uzlů Row a poté uzlů Cell. V objektovém modelu Document Aspose.Words, stejně jako v dokumentech Word, tedy neexistuje koncept sloupce.

Podle návrhu jsou řádky tabulky v Microsoft Word a Aspose.Words zcela nezávislé a základní vlastnosti a operace jsou obsaženy pouze v řádcích a buňkách tabulky. To dává tabulkám možnost mít některé zajímavé atributy:

  • Každý řádek tabulky může mít zcela jiný počet buněk
  • Vertikálně mohou mít buňky každého řádku různé šířky
  • Je možné spojit tabulky s různými formáty řádků a počtem buněk

Jakékoli operace prováděné na sloupcích jsou ve skutečnosti “zkratky”, které provádějí operaci kolektivní změnou buněk řádků takovým způsobem, že to vypadá, že se aplikují na sloupce. To znamená, že můžete provádět operace se sloupci jednoduše iterací přes stejný index buněk řádku tabulky.

Následující příklad kódu zjednodušuje takové operace prokázáním třídy fasád, která shromažďuje buňky, které tvoří “sloupec” tabulky:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
/// <summary>
/// Represents a facade object for a column of a table in a Microsoft Word document.
/// </summary>
class Column : public System::Object
{
public:
/// <summary>
/// Returns the cells which make up the column.
/// </summary>
ArrayPtr<SharedPtr<Cell>> get_Cells()
{
return GetColumnCells()->ToArray();
}
/// <summary>
/// Returns a new column facade from the table and supplied zero-based index.
/// </summary>
static SharedPtr<WorkingWithTables::Column> FromIndex(SharedPtr<Table> table, int columnIndex)
{
return WorkingWithTables::Column::MakeObject(table, columnIndex);
}
/// <summary>
/// Returns the index of the given cell in the column.
/// </summary>
int IndexOf(SharedPtr<Cell> cell)
{
return GetColumnCells()->IndexOf(cell);
}
/// <summary>
/// Inserts a brand new column before this column into the table.
/// </summary>
SharedPtr<WorkingWithTables::Column> InsertColumnBefore()
{
ArrayPtr<SharedPtr<Cell>> columnCells = get_Cells();
if (columnCells->get_Length() == 0)
{
throw System::ArgumentException(u"Column must not be empty");
}
// Create a clone of this column.
for (SharedPtr<Cell> cell : columnCells)
{
cell->get_ParentRow()->InsertBefore(cell->Clone(false), cell);
}
// This is the new column.
auto column = WorkingWithTables::Column::MakeObject(columnCells[0]->get_ParentRow()->get_ParentTable(), mColumnIndex);
// We want to make sure that the cells are all valid to work with (have at least one paragraph).
for (SharedPtr<Cell> cell : column->get_Cells())
{
cell->EnsureMinimum();
}
// Increase the index which this column represents since there is now one extra column in front.
mColumnIndex++;
return column;
}
/// <summary>
/// Removes the column from the table.
/// </summary>
void Remove()
{
for (SharedPtr<Cell> cell : get_Cells())
{
cell->Remove();
}
}
/// <summary>
/// Returns the text of the column.
/// </summary>
String ToTxt()
{
auto builder = System::MakeObject<System::Text::StringBuilder>();
for (SharedPtr<Cell> cell : get_Cells())
{
builder->Append(cell->ToString(SaveFormat::Text));
}
return builder->ToString();
}
private:
int mColumnIndex;
SharedPtr<Table> mTable;
Column(SharedPtr<Table> table, int columnIndex) : mColumnIndex(0)
{
if (table == nullptr)
{
throw System::ArgumentException(u"table");
}
mTable = table;
mColumnIndex = columnIndex;
}
MEMBER_FUNCTION_MAKE_OBJECT(Column, CODEPORTING_ARGS(SharedPtr<Table> table, int columnIndex), CODEPORTING_ARGS(table, columnIndex));
/// <summary>
/// Provides an up-to-date collection of cells which make up the column represented by this facade.
/// </summary>
SharedPtr<System::Collections::Generic::List<SharedPtr<Cell>>> GetColumnCells()
{
SharedPtr<System::Collections::Generic::List<SharedPtr<Cell>>> columnCells =
System::MakeObject<System::Collections::Generic::List<SharedPtr<Cell>>>();
for (const auto& row : System::IterateOver<Row>(mTable->get_Rows()))
{
SharedPtr<Cell> cell = row->get_Cells()->idx_get(mColumnIndex);
if (cell != nullptr)
{
columnCells->Add(cell);
}
}
return columnCells;
}
};
view raw column-class.h hosted with ❤ by GitHub

Následující příklad kódu ukazuje, jak vložit prázdný sloupec do tabulky:

// 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));
SharedPtr<WorkingWithTables::Column> column = WorkingWithTables::Column::FromIndex(table, 0);
// Print the plain text of the column to the screen.
std::cout << column->ToTxt() << std::endl;
// Create a new column to the left of this column.
// This is the same as using the "Insert Column Before" command in Microsoft Word.
SharedPtr<WorkingWithTables::Column> newColumn = column->InsertColumnBefore();
for (SharedPtr<Cell> cell : newColumn->get_Cells())
{
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, String(u"Column Text ") + newColumn->IndexOf(cell)));
}

Následující příklad kódu ukazuje, jak odebrat sloupec z tabulky v dokumentu:

// 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, 1, true));
SharedPtr<WorkingWithTables::Column> column = WorkingWithTables::Column::FromIndex(table, 2);
column->Remove();
view raw remove-column.h hosted with ❤ by GitHub

Určete řádky jako řádky záhlaví

Můžete se rozhodnout opakovat první řádek v tabulce jako řádek záhlaví pouze na první stránce nebo na každé stránce, pokud je tabulka rozdělena na několik. V Aspose.Words můžete opakovat řádek záhlaví na každé stránce pomocí vlastnosti HeadingFormat.

Můžete také označit více řádků záhlaví, pokud jsou tyto řádky umístěny jeden po druhém na začátku tabulky. Chcete-li to provést, musíte na tyto řádky použít vlastnosti HeadingFormat.

Následující příklad kódu ukazuje, jak vytvořit tabulku, která obsahuje řádky záhlaví, které se opakují na následujících stránkách:

// 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);
builder->StartTable();
builder->get_RowFormat()->set_HeadingFormat(true);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->set_Width(100);
builder->InsertCell();
builder->Writeln(u"Heading row 1");
builder->EndRow();
builder->InsertCell();
builder->Writeln(u"Heading row 2");
builder->EndRow();
builder->get_CellFormat()->set_Width(50);
builder->get_ParagraphFormat()->ClearFormatting();
for (int i = 0; i < 50; i++)
{
builder->InsertCell();
builder->get_RowFormat()->set_HeadingFormat(false);
builder->Write(u"Column 1 Text");
builder->InsertCell();
builder->Write(u"Column 2 Text");
builder->EndRow();
}
doc->Save(ArtifactsDir + u"WorkingWithTables.RepeatRowsOnSubsequentPages.docx");

Zabraňte lámání tabulek a řádků napříč stránkami

Jsou chvíle, kdy by obsah tabulky neměl být rozdělen mezi stránky. Pokud je například název nad tabulkou, měl by být název a tabulka vždy drženy pohromadě na stejné stránce, aby byl zachován správný vzhled.

K dosažení této funkce jsou užitečné dvě samostatné techniky:

  • Allow row break across pages, který se použije na řádky tabulky
  • Keep with next, který se použije na odstavce v buňkách tabulky

Ve výchozím nastavení jsou výše uvedené vlastnosti zakázány.

Zabraňte lámání řádku mezi stránkami

To zahrnuje omezení rozdělení obsahu uvnitř buněk řádku na stránku. V Microsoft Word to lze nalézt pod vlastnostmi tabulky jako možnost “Povolit zalomení řádku mezi stránkami”. V Aspose.Words se to nachází pod RowFormat objektem Row jako vlastnost RowFormat.AllowBreakAcrossPages.

Následující příklad kódu ukazuje, jak zakázat lámání řádků napříč stránkami pro každý řádek v 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"Table spanning two pages.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Disable breaking across pages for all rows in the table.
for (const auto& row : System::IterateOver<Row>(table->get_Rows()))
{
row->get_RowFormat()->set_AllowBreakAcrossPages(false);
}
doc->Save(ArtifactsDir + u"WorkingWithTables.RowFormatDisableBreakAcrossPages.docx");

Zabraňte rozbití tabulky mezi stránkami

Abychom zabránili rozdělení tabulky mezi stránky, musíme určit, že chceme, aby obsah obsažený v tabulce zůstal pohromadě.

Chcete-li to provést, Aspose.Words používá metodu, která umožňuje uživatelům vybrat tabulku a povolit parametr KeepWithNext na hodnotu true pro každý odstavec v buňkách tabulky. Výjimkou je poslední odstavec v tabulce, který by měl být nastaven na hodnotu false.

Následující příklad kódu ukazuje, jak nastavit tabulku tak, aby zůstala pohromadě na stejné stránce:

// 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"Table spanning two pages.docx");
auto table = System::ExplicitCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// We need to enable KeepWithNext for every paragraph in the table to keep it from breaking across a page,
// except for the last paragraphs in the last row of the table.
for (const auto& cell : System::IterateOver<Cell>(table->GetChildNodes(NodeType::Cell, true)))
{
cell->EnsureMinimum();
for (const auto& para : System::IterateOver<Paragraph>(cell->get_Paragraphs()))
{
if (!(cell->get_ParentRow()->get_IsLastRow() && para->get_IsEndOfCell()))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
}
}
doc->Save(ArtifactsDir + u"WorkingWithTables.KeepTableTogether.docx");