使用列和行

要更好地控制表的工作方式,请了解如何操作列和行。

查找表元素索引

通过索引访问选定的文档节点来管理列、行和单元格。查找任意节点的索引涉及从父节点收集该元素类型的所有子节点,然后使用 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 节点组成。因此,在 Aspose.Words 的 Document 对象模型中,就像在 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,应用于表格单元格中的段落

默认情况下,上述属性被禁用。

防止行跨页中断

这涉及限制行单元格内的内容在页面上拆分。在 Microsoft Word 中,可以在"表属性"下找到"允许跨页断行"选项。在 Aspose.Words 中,可以在 RowRowFormat 对象下找到该属性,作为属性 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")

防止表格跨页断裂

为了阻止表格跨页拆分,我们需要指定希望表格中包含的内容保持在一起。

为此,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")