Робота з колонами та рядками
Для більшого контролю над роботою таблиць вивчіть, як маніпулювати стовпчики і рядки.
Знайти Індекс елемента таблиці
Колонки, рядки та клітини керовані шляхом доступу до вибраного вузла документа індексом. Пошук індексу будь-якого вузла передбачає збирання всіх дочірніх вузлів елемента з материнської вершини, а потім використання IndexOf метод пошуку індексу необхідного вузла в збірнику.
Знайти Індекс таблиці в документі
Іноді необхідно внести зміни до певного столу в документі. Для цього можна звернутися до таблиці за його індексом.
Приклад наступного коду показує, як отримати індекс таблиці в документі:
// 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); |
Знаходження Індексу Row в таблиці
Аналогічно можна внести зміни в конкретний ряд у вибраному столі. Щоб зробити це, ви також можете звернутися до ряду за його індексом.
Приклад наступного коду показує, як отримати індекс рядка в таблиці:
// 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()); |
Знаходження Індексу клітини в рядку
Нарешті, ви можете змінити конкретну клітинку, і ви можете зробити це за допомогою індексу клітин.
Приклад наступного коду показує, як отримати індекс клітинки в рядку:
// 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)); |
Робота з колонами
У Aspose.Words Document Object Model (Українська)DOMй Table вузол складається з Row вузли і потім Cell вершини. Так, в Document
Модель об’єкта Aspose.Words, як у документах Word немає поняття стовпця.
По дизайну, таблиці рядків в Microsoft Word і Aspose.Words повністю самостійні, а основні властивості і операції містяться тільки в рядах і клітинах таблиці. Це дає таблиці можливість мати деякі цікаві атрибути:
- Кожний ряд таблиці може мати абсолютно різну кількість клітин
- Вертикально, клітини кожного ряду можуть мати різні ширини
- до Включити таблиці з різними форматами рядків і кількістю клітин
Будь-які операції, які виконуються на стовпцях, насправді “коротки”, які виконують роботу колективно змінними клітинами рядка таким чином, що вона виглядає, як вони наносяться на стовпці. Таким чином, ви можете виконувати операції по стовпцях, просто ітеруючи над тим же індексом клітинного рядка.
Прикладом такого коду спрощує такі операції, даючи фасадний клас, який збирає клітини, які складають “холодний” таблиці:
// 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; | |
} |
Приклад коду показує, як вставити порожній стовпчик в таблицю:
// 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))); |
Приклад наступного коду показує, як видалити стовпчик з таблиці в документі:
// 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(); |
Вказати рядки як головка
Ви можете вибрати для повторення першого ряду в таблиці як заголовок, тільки на першій сторінці або на кожній сторінці, якщо таблиця розщеплюється на кілька. У Aspose.Words, Ви можете повторити заголовок на кожній сторінці за допомогою сторінки HeadingFormat майно.
Ви також можете відмітити кілька рядків заголовка, якщо такі рядки розташовані один після іншого на початку столу. Для цього потрібно застосувати HeadingFormat властивості до цих рядів.
Приклад наступного коду показує, як побудувати таблицю, яка включає в себе Головні рядки, які повторюються на наступних сторінках:
// 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"); |
Тримайте таблиці та рядки від Breaking Across Сторінки
Часом, де вміст таблиці не повинно бути розщеплення по сторінках. Наприклад, якщо заголовок вище таблиці, заголовок та таблиці завжди повинні зберігатися разом на одній сторінці для збереження належного зовнішнього вигляду.
Є дві окремі техніки, які корисні для досягнення цієї функціональності:
- до
Allow row break across pages
, який наноситься на рядки таблиці - до
Keep with next
, який наноситься на абзаци в клітинах таблиці
За замовчуванням вищевказані властивості вимкнено.

Зберігати Row від Breaking Across Сторінки
Це передбачає обмеження вмісту всередині клітин рядка від розщеплення по всій сторінці. У Microsoft Word, Це може бути знайдений під Table Properties як варіант “Всі ряди для розбиття по сторінках”. У Aspose.Words це знайдено під RowFormat об’єкт об’єкта Row як майно RowFormat.AllowBreakAcrossPagesй

Наприклад, наступний код показує, як відключити розрив рядків по сторінках кожного ряду в таблиці:
// 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"); |
Тримайте таблицю від перервованих сторінок Across
Щоб зупинити таблицю з розщеплення по сторінках, потрібно вказати, що ми хочемо, щоб вміст, що міститься в таблиці, щоб триматися разом.
Для цього Aspose.Words використовує метод, який дозволяє користувачам вибрати таблицю і увімкнути таблицю KeepWithNext параметр до true для кожного абзацу в клітинках таблиці. Виняток - останній пункт в таблиці, який повинен бути встановлений для falseй

Приклад коду показує, як встановити таблицю, щоб триматися разом на одній сторінці:
// 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"); |