Práce se sloupci a řádky

Pro větší kontrolu nad tím, jak stoly fungují, se naučte manipulovat sloupy a řádky.

Najít index prvků tabulky

Sloupce, řádky a buňky jsou řízeny přístupem k vybranému uzelu dokumentu svým indexem. Nalezení indexu jakéhokoliv uzlu zahrnuje shromažďování všech dětských uzlů typu prvku z rodičovského uzlu, a pak pomocí IndexOf metoda pro nalezení indexu požadovaného uzelu v kolekci.

Najít index tabulky v dokumentu

Někdy je třeba změnit konkrétní tabulku v dokumentu. Chcete-li to udělat, můžete odkazovat na tabulku podle jejího indexu.

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
int tableIndex = allTables.indexOf(table);

Nalezení indexu řádku v tabulce

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

Následující příklad kódu ukazuje, jak získat index řádku v tabulce:

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

Nalezení indexu buňky v řadě

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
int cellIndex = row.indexOf(row.getCells().get(4));

Práce se sloupy

V Aspose.Words Document Object Model (DOM), Table Uzel se skládá z Row uzly a pak Cell uzly. Proto v Document Model objektu Aspose.Words, jako v dokumentu Word, neexistuje pojem sloupce.

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

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

work-with-columns-aspose-words-java

Veškeré operace prováděné na sloupcích jsou ve skutečnosti “krátké zkratky,” které provádějí operaci kolektivně měnícími se řádkovými buňkami tak, aby to vypadalo, že jsou aplikovány na sloupce. To znamená, že můžete provádět operace na sloupcích jednoduše iterací nad stejným indexem buňky řádku tabulky.

Následující příklad kódu tyto operace zjednodušuje prokázáním třídy fasády, 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-Java.git.
/// <summary>
/// Represents a facade object for a column of a table in a Microsoft Word document.
/// </summary>
static class Column
{
private Column(Table table, int columnIndex) {
if (table != null) {
mTable = table;
} else {
throw new IllegalArgumentException("table");
}
mColumnIndex = columnIndex;
}
/// <summary>
/// Returns a new column facade from the table and supplied zero-based index.
/// </summary>
public static Column fromIndex(Table table, int columnIndex)
{
return new Column(table, columnIndex);
}
private ArrayList<Cell> getCells() {
return getColumnCells();
}
/// <summary>
/// Returns the index of the given cell in the column.
/// </summary>
public int indexOf(Cell cell)
{
return getColumnCells().indexOf(cell);
}
/// <summary>
/// Inserts a brand new column before this column into the table.
/// </summary>
public Column insertColumnBefore()
{
ArrayList<Cell> columnCells = getCells();
if (columnCells.size() == 0)
throw new IllegalArgumentException("Column must not be empty");
// Create a clone of this column.
for (Cell cell : columnCells)
cell.getParentRow().insertBefore(cell.deepClone(false), cell);
// This is the new column.
Column column = new Column(columnCells.get(0).getParentRow().getParentTable(), mColumnIndex);
// We want to make sure that the cells are all valid to work with (have at least one paragraph).
for (Cell cell : column.getCells())
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>
public void remove()
{
for (Cell cell : getCells())
cell.remove();
}
/// <summary>
/// Returns the text of the column.
/// </summary>
public String toTxt() throws Exception
{
StringBuilder builder = new StringBuilder();
for (Cell cell : getCells())
builder.append(cell.toString(SaveFormat.TEXT));
return builder.toString();
}
/// <summary>
/// Provides an up-to-date collection of cells which make up the column represented by this facade.
/// </summary>
private ArrayList<Cell> getColumnCells()
{
ArrayList<Cell> columnCells = new ArrayList<Cell>();
for (Row row : mTable.getRows())
{
Cell cell = row.getCells().get(mColumnIndex);
if (cell != null)
columnCells.add(cell);
}
return columnCells;
}
private int mColumnIndex;
private Table mTable;
}

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-Java.git.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
Column column = Column.fromIndex(table, 0);
// Print the plain text of the column to the screen.
System.out.println(column.toTxt());
// Create a new column to the left of this column.
// This is the same as using the "Insert Column Before" command in Microsoft Word.
Column newColumn = column.insertColumnBefore();
for (Cell cell : newColumn.getColumnCells())
cell.getFirstParagraph().appendChild(new Run(doc, "Column Text " + newColumn.indexOf(cell)));

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 1, true);
Column column = Column.fromIndex(table, 2);
column.remove();

Upřesnit řádky jako řádky záhlaví

První řádek tabulky můžete zopakovat jako řádek záhlaví pouze na první stránce nebo na každé stránce, pokud je tabulka rozdělena do několika. In Aspose.Words, můžete opakovat řádek záhlaví na každé stránce pomocí HeadingFormat majetek.

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

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-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startTable();
builder.getRowFormat().setHeadingFormat(true);
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.getCellFormat().setWidth(100.0);
builder.insertCell();
builder.writeln("Heading row 1");
builder.endRow();
builder.insertCell();
builder.writeln("Heading row 2");
builder.endRow();
builder.getCellFormat().setWidth(50.0);
builder.getParagraphFormat().clearFormatting();
for (int i = 0; i < 50; i++)
{
builder.insertCell();
builder.getRowFormat().setHeadingFormat(false);
builder.write("Column 1 Text");
builder.insertCell();
builder.write("Column 2 Text");
builder.endRow();
}
doc.save(getArtifactsDir() + "WorkingWithTables.RepeatRowsOnSubsequentPages.docx");

Udržet tabulky a řádky od prolomení napříč stránkami

Jsou chvíle, kdy by obsah tabulky neměl být rozdělen přes stránky. Například pokud je titul nad tabulkou, měl by být název a tabulka vždy na stejné stránce, aby se zachoval správný vzhled.

Existují dvě samostatné techniky, které jsou užitečné pro dosažení této funkce:

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

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

keep-tables-and-rows-from-breaking-across-pages-aspose-words-java

Udržet řadu od prolomení napříč stránkami

To zahrnuje omezení obsahu uvnitř buněk řady od rozdělení přes stránku. In Microsoft Word, to lze nalézt v Tabulce Vlastnosti jako možnost ¶Allow row to break across page'. In Aspose.Words Toto je nalezeno pod RowFormat objekt a Row jako majetek RowFormat.AllowBreakAcrossPages.

keep-rows-from-breaking-across-pages-aspose-words-java

Následující příklad kódu ukazuje, jak zakázat rozbíjení řá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-Java.git.
Document doc = new Document(getMyDir() + "Table spanning two pages.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
// Disable breaking across pages for all rows in the table.
for (Row row : (Iterable<Row>) table.getRows())
row.getRowFormat().setAllowBreakAcrossPages(false);
doc.save(getArtifactsDir() + "WorkingWithTables.RowFormatDisableBreakAcrossPages.docx");

Udržet stůl od prolomení napříč stránkami

Abychom zastavili rozdělení tabulky napříč stránkami, musíme upřesnit, že chceme, aby obsah obsažený v tabulce zůstal pohromadě.

Abych to udělal, Aspose.Words používá metodu, která umožňuje uživatelům vybrat tabulku a povolit KeepWithNext parametr do true pro každý odstavec uvnitř buněk tabulky. Výjimkou je poslední odstavec tabulky, který by měl být stanoven false.

keep-tables-from-breaking-across-pages-aspose-words-java

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Table spanning two pages.docx");
Table table = (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 (Cell cell : (Iterable<Cell>) table.getChildNodes(NodeType.CELL, true))
{
cell.ensureMinimum();
for (Paragraph para : (Iterable<Paragraph>) cell.getParagraphs())
if (!(cell.getParentRow().isLastRow() && para.isEndOfCell()))
para.getParagraphFormat().setKeepWithNext(true);
}
doc.save(getArtifactsDir() + "WorkingWithTables.KeepTableTogether.docx");