Praca z kolumnami i wierszami

Aby uzyskać większą kontrolę nad funkcjonowaniem tabel, naucz się manipulować kolumnami i wierszami.

Znajdź indeks elementu tabeli

Kolumny, wiersze i komórki są zarządzane przez dostęp do wybranego węzła dokumentu przez jego indeks. Znalezienie indeksu dowolnego węzła polega na zebraniu wszystkich węzłów dziecięcych typu elementu z węzła macierzystego, a następnie użyciu IndexOf metoda znalezienia indeksu pożądanego węzła w kolekcji.

Znajdź indeks tabeli w dokumencie

Czasami może być konieczne wprowadzenie zmian do konkretnej tabeli w dokumencie. Aby to zrobić, można odnieść się do tabeli po jej indeksie.

Poniższy przykład kodu pokazuje jak pobrać indeks tabeli w dokumencie:

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

Znalezienie indeksu wiersza w tabeli

Podobnie może być konieczne wprowadzenie zmian do określonego wiersza w wybranej tabeli. Aby to zrobić, możesz również odnieść się do wiersza po jego indeksie.

Poniższy przykład kodu pokazuje jak pobrać indeks wiersza w tabeli:

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

Znalezienie indeksu komórki w wierszu

Wreszcie, może trzeba wprowadzić zmiany do konkretnej komórki, i można to zrobić również przez indeks komórki.

Poniższy przykład kodu pokazuje, jak pobrać indeks komórki w wierszu:

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

Praca z kolumnami

W Aspose.Words Document Object Model (DOM), Table węzeł składa się z Row węzły, a następnie Cell węzły. Tak więc, w Document Model obiektu Aspose.Words, jak w dokumentach Worda, nie ma pojęcia o kolumnie.

Według projektu, tabeli wiersze w Microsoft Word oraz Aspose.Words są całkowicie niezależne, a podstawowe właściwości i operacje są zawarte tylko w wierszach i komórkach tabeli. Daje to tabelom możliwość posiadania ciekawych atrybutów:

  • Każdy rząd tabeli może mieć zupełnie inną liczbę komórek
  • pionowo, komórki każdego rzędu mogą mieć różne szerokości
  • Istnieje możliwość łączenia tabel z różnymi formatami wierszy i liczbą komórek

work-with-columns-aspose-words-java

Wszelkie operacje wykonywane na kolumnach są rzeczywiście “skrótami”, które wykonują operację poprzez zbiorczą zmianę komórek wierszy w taki sposób, że wygląda na to, że są one stosowane do kolumn. Oznacza to, że można wykonywać operacje na kolumnach, po prostu powtarzając ten sam indeks komórek wiersza tabeli.

Poniższy przykład kodu upraszcza takie operacje, udowadniając klasę elewacji, która zbiera komórki, które tworzą “kolumnę” tabeli:

// 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;
}

Poniższy przykład kodu pokazuje jak umieścić pustą kolumnę w tabeli:

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

Poniższy przykład kodu pokazuje jak usunąć kolumnę z tabeli w dokumencie:

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

Określa wiersze jako wiersze nagłówka

Możesz powtórzyć pierwszy wiersz w tabeli jako wiersz nagłówka tylko na pierwszej stronie lub na każdej stronie, jeśli tabela jest podzielona na kilka. W Aspose.Words, możesz powtórzyć wiersz nagłówka na każdej stronie za pomocą HeadingFormat nieruchomości.

Możesz również zaznaczyć wiele wierszy nagłówka, jeśli takie wiersze znajdują się jeden za drugim na początku tabeli. Aby to zrobić, należy zastosować HeadingFormat właściwości tych wierszy.

Poniższy przykład kodu pokazuje jak zbudować tabelę zawierającą wiersze nagłówka, które powtarzają się na kolejnych stronach:

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

Zachowaj tabele i wiersze z przełamywania stron

Istnieją momenty, w których zawartość tabeli nie powinna być podzielona na strony. Na przykład, jeśli tytuł jest powyżej tabeli, tytuł i tabela powinny być zawsze trzymane razem na tej samej stronie, aby zachować odpowiedni wygląd.

Istnieją dwa odrębne techniki, które są przydatne do osiągnięcia tej funkcjonalności:

  • Allow row break across pages, które stosuje się do wierszy tabeli
  • Keep with next, które stosuje się do ustępów w komórkach tabeli

Domyślnie powyższe właściwości są wyłączone.

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

Keep a row from Breaking Across Pages

Oznacza to ograniczenie zawartości wewnątrz komórek wiersza do podziału na stronę. W Microsoft Word, to można znaleźć w Właściwości tabeli jako opcja “Zezwalaj na przełamanie wiersza między stronami”. W Aspose.Words to znajduje się pod RowFormat obiekt Row jako nieruchomość RowFormat.AllowBreakAcrossPages.

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

Poniższy przykład kodu pokazuje jak wyłączyć łamanie wierszy pomiędzy stronami dla każdego wiersza tabeli:

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

Zachowaj stół przed przełamywaniem stron

Aby zatrzymać podział tabeli na strony, musimy określić, że chcemy, aby zawartość w tabeli pozostać razem.

Aby to zrobić, Aspose.Words używa metody, która pozwala użytkownikom wybrać tabelę i włączyć KeepWithNext parametr true dla każdego punktu w komórkach tabeli. Wyjątkiem jest ostatni akapit tabeli, który należy ustawić na false.

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

Poniższy przykład kodu pokazuje, jak ustawić tabelę, aby pozostać razem na tej samej stronie:

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