Робота з колонами та рядками

Для більшого контролю над тим, як працюють таблиці, вивчіть, як маніпулювати стовпчики і рядки.

Знайти Індекс елемента таблиці

Колонки, рядки та клітини керовані шляхом доступу до вибраного вузла документа індексом. Пошук індексу будь-якого вузла передбачає збирання всіх дочірніх вузлів елемента з материнської вершини, а потім використання IndexOf метод пошуку індексу необхідного вузла в збірнику.

Знайти Індекс таблиці в документі

Іноді необхідно внести зміни до певного столу в документі. Для цього можна звернутися до таблиці за його індексом.

Приклад наступного коду показує, як отримати індекс таблиці в документі:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table()
all_tables = doc.get_child_nodes(aw.NodeType.TABLE, True)
table_index = all_tables.index_of(table)

Пошук Індексу Рів у таблиці

Аналогічно можна внести зміни в конкретний ряд у вибраному столі. Для цього можна також звернутися до ряду за його індексом.

Приклад наступного коду показує, як отримати індекс рядка в таблиці:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
row_index = table.index_of(table.last_row)

Знаходження Індексу клітини в рядку

Нарешті, ви можете змінити певну клітинку, і ви можете зробити це за допомогою індексу клітин.

Приклад наступного коду показує, як отримати індекс клітинки в рядку:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
cell_index = row.index_of(row.cells[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-Python-via-.NET.git.
class Column:
"""Represents a facade object for a column of a table in a Microsoft Word document."""
def __init__(self, table: aw.tables.Table, column_index: int):
if table is None:
raise ValueError("table")
self.table = table
self.column_index = column_index
def index_of(self, cell: aw.tables.Cell):
"""Returns the index of the given cell in the column."""
return self.get_column_cells().index(cell)
def insert_column_before(self):
"""Inserts a brand new column before this column into the table."""
column_cells = self.get_column_cells()
if len(column_cells) == 0:
raise ValueError("Column must not be empty")
# Create a clone of this column.
for cell in column_cells:
cell.parent_row.insert_before(cell.clone(False), cell)
# This is the new column.
column = self.__class__(column_cells[0].parent_row.parent_table, self.column_index)
# We want to make sure that the cells are all valid to work with (have at least one paragraph).
for cell in column.get_column_cells():
cell.ensure_minimum()
# Increase the index which this column represents since there is now one extra column in front.
self.column_index += 1
return column
def remove(self):
"""Removes the column from the table."""
for cell in self.get_column_cells():
cell.remove()
def to_txt(self):
"""Returns the text of the column."""
return "".join(cell.to_string(aw.SaveFormat.TEXT) for cell in self.get_column_cells())
def get_column_cells(self):
"""Provides an up-to-date collection of cells which make up the column represented by this facade."""
column_cells = []
for row in self.table.rows:
cell = row.as_row().cells[self.column_index]
if cell is not None:
column_cells.append(cell)
return column_cells
view raw column-class.py hosted with ❤ by GitHub

Приклад наступного коду показує, як вставити порожній стовпчик в таблицю:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document(MY_DIR + "Tables.docx")
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table()
column = self.Column(table, 0)
# Print the plain text of the column to the screen.
print(column.to_txt())
# Create a new column to the left of this column.
# This is the same as using the "Insert Column Before" command in Microsoft Word.
new_column = column.insert_column_before()
for cell in new_column.get_column_cells():
cell.first_paragraph.append_child(aw.Run(doc, "Column Text " + str(new_column.index_of(cell))))

Приклад наступного коду показує, як видалити стовпчик з таблиці в документі:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document(MY_DIR + "Tables.docx")
table = doc.get_child(aw.NodeType.TABLE, 1, True).as_table()
column = self.Column(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-Python-via-.NET.git.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.start_table()
builder.row_format.heading_format = True
builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
builder.cell_format.width = 100
builder.insert_cell()
builder.writeln("Heading row 1")
builder.end_row()
builder.insert_cell()
builder.writeln("Heading row 2")
builder.end_row()
builder.cell_format.width = 50
builder.paragraph_format.clear_formatting()
for _ in range(50):
builder.insert_cell()
builder.row_format.heading_format = False
builder.write("Column 1 Text")
builder.insert_cell()
builder.write("Column 2 Text")
builder.end_row()
doc.save(ARTIFACTS_DIR + "WorkingWithTables.repeat_rows_on_subsequent_pages.docx")

Тримайте таблиці та рядки від перерв на сторінках

Часом, де вміст таблиці не повинно бути розщеплення по сторінках. Наприклад, якщо заголовок вище таблиці, заголовок та таблиці завжди слід тримати разом на одній сторінці, щоб зберегти правильний вигляд.

Є дві окремі техніки, які корисні для досягнення цієї функціональності:

  • до 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-Python-via-.NET.git.
doc = aw.Document(MY_DIR + "Table spanning two pages.docx")
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table()
# Disable breaking across pages for all rows in the table.
for row in table.rows:
row.as_row().row_format.allow_break_across_pages = False
doc.save(ARTIFACTS_DIR + "WorkingWithTables.row_format_disable_break_across_pages.docx")

Тримайте таблицю з розірвання сторінок Across

Щоб зупинити таблицю з розщеплення по сторінках, потрібно вказати, що ми хочемо, щоб вміст, що міститься в таблиці, щоб триматися разом.

Для цього Aspose.Words використовує метод, який дозволяє користувачам вибрати таблицю і увімкнути таблицю KeepWithNext параметр до true для кожного абзацу в клітинках таблиці. Виняток є останню абзацу в таблиці, яка повинна бути встановлена до falseй

Приклад наступного коду показує, як встановити таблицю, щоб триматися разом на одній сторінці:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document(MY_DIR + "Table spanning two pages.docx")
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table()
# 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 in table.get_child_nodes(aw.NodeType.CELL, True):
cell = cell.as_cell()
cell.ensure_minimum()
for para in cell.paragraphs:
para = para.as_paragraph()
if not (cell.parent_row.is_last_row and para.is_end_of_cell):
para.paragraph_format.keep_with_next = True
doc.save(ARTIFACTS_DIR + "WorkingWithTables.keep_table_together.docx")