Введение и создание таблиц

Aspose.Words позволяет пользователям создавать таблицы в документе с нуля и предоставляет несколько различных методов для этого. В этой статье представлены подробные сведения о том, как добавлять отформатированные таблицы в документ, используя каждый из методов, а также сравнение каждого метода в конце статьи.

Стили таблиц по умолчанию

Вновь созданной таблице присваиваются значения по умолчанию, аналогичные тем, которые используются в Microsoft Word:

Свойство таблицы Значение по умолчанию в Aspose.Words
Border Style Single
Border Width 1/2 pt
Border Color Black
Left and Right Padding 5.4 pts
AutoFit Mode AutoFit to Window
Allow AutoFit True

Создайте таблицу с DocumentBuilder

В Aspose.Words пользователи могут создать таблицу в документе, используя DocumentBuilder. Основной алгоритм создания таблицы следующий:

  1. Начните таблицу с StartTable
  2. Добавьте ячейку в таблицу, используя InsertCell – при этом автоматически начнется новая строка
  3. При необходимости используйте свойство CellFormat, чтобы задать форматирование ячеек
  4. Вставьте содержимое ячейки, используя соответствующие методы DocumentBuilder, такие как Writeln, InsertImage и другие
  5. Повторяйте шаги 2-4, пока строка не будет завершена
  6. Вызовите EndRow, чтобы завершить текущую строку
  7. При необходимости используйте свойство RowFormat, чтобы задать форматирование строк
  8. Повторяйте шаги 2-7 до тех пор, пока таблица не будет заполнена
  9. Вызовите EndTable, чтобы завершить построение таблицы

Процесс создания таблицы можно наглядно увидеть на следующем рисунке:

creating-table-process

В следующем примере кода показано, как создать простую таблицу, используя DocumentBuilder с форматированием по умолчанию:

# 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)
# Start building the table.
builder.start_table()
builder.insert_cell()
builder.write("Row 1, Cell 1 Content.")
# Build the second cell.
builder.insert_cell()
builder.write("Row 1, Cell 2 Content.")
# Call the following method to end the row and start a new row.
builder.end_row()
# Build the first cell of the second row.
builder.insert_cell()
builder.write("Row 2, Cell 1 Content")
# Build the second cell.
builder.insert_cell()
builder.write("Row 2, Cell 2 Content.")
builder.end_row()
# Signal that we have finished building the table.
builder.end_table()
doc.save(ARTIFACTS_DIR + "WorkingWithTables.create_simple_table.docx")

В следующем примере кода показано, как создать отформатированную таблицу, используя DocumentBuilder:

# 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)
table = builder.start_table()
builder.insert_cell()
# Table wide formatting must be applied after at least one row is present in the table.
table.left_indent = 20.0
# Set height and define the height rule for the header row.
builder.row_format.height = 40.0
builder.row_format.height_rule = aw.HeightRule.AT_LEAST
builder.cell_format.shading.background_pattern_color = drawing.Color.from_argb(198, 217, 241)
builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
builder.font.size = 16
builder.font.name = "Arial"
builder.font.bold = True
builder.cell_format.width = 100.0
builder.write("Header Row,\n Cell 1")
# We don't need to specify this cell's width because it's inherited from the previous cell.
builder.insert_cell()
builder.write("Header Row,\n Cell 2")
builder.insert_cell()
builder.cell_format.width = 200.0
builder.write("Header Row,\n Cell 3")
builder.end_row()
builder.cell_format.shading.background_pattern_color = drawing.Color.white
builder.cell_format.width = 100.0
builder.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER
# Reset height and define a different height rule for table body.
builder.row_format.height = 30.0
builder.row_format.height_rule = aw.HeightRule.AUTO
builder.insert_cell()
# Reset font formatting.
builder.font.size = 12
builder.font.bold = False
builder.write("Row 1, Cell 1 Content")
builder.insert_cell()
builder.write("Row 1, Cell 2 Content")
builder.insert_cell()
builder.cell_format.width = 200.0
builder.write("Row 1, Cell 3 Content")
builder.end_row()
builder.insert_cell()
builder.cell_format.width = 100.0
builder.write("Row 2, Cell 1 Content")
builder.insert_cell()
builder.write("Row 2, Cell 2 Content")
builder.insert_cell()
builder.cell_format.width = 200.0
builder.write("Row 2, Cell 3 Content.")
builder.end_row()
builder.end_table()
doc.save(ARTIFACTS_DIR + "WorkingWithTables.formatted_table.docx")

В следующем примере кода показано, как вставить вложенную таблицу, используя DocumentBuilder:

# 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)
cell = builder.insert_cell()
builder.writeln("Outer Table Cell 1")
builder.insert_cell()
builder.writeln("Outer Table Cell 2")
# This call is important to create a nested table within the first table.
# Without this call, the cells inserted below will be appended to the outer table.
builder.end_table()
# Move to the first cell of the outer table.
builder.move_to(cell.first_paragraph)
# Build the inner table.
builder.insert_cell()
builder.writeln("Inner Table Cell 1")
builder.insert_cell()
builder.writeln("Inner Table Cell 2")
builder.end_table()
doc.save(ARTIFACTS_DIR + "WorkingWithTables.nested_table.docx")
view raw nested-table.py hosted with ❤ by GitHub

Создайте таблицу с помощью DOM (объектная модель документа)

Вы можете вставить таблицы непосредственно в DOM, добавив новый узел Table в определенном месте.

Обратите внимание, что сразу после создания узла таблицы сама таблица будет полностью пустой, то есть в ней еще не будет строк и ячеек. Чтобы вставить строки и ячейки в таблицу, добавьте соответствующие дочерние узлы Row и Cell в DOM.

В следующем примере кода показано, как создать новую таблицу с нуля, добавив соответствующие дочерние узлы в дерево документа:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
# We start by creating the table object. Note that we must pass the document object
# to the constructor of each node. This is because every node we create must belong
# to some document.
table = aw.tables.Table(doc)
doc.first_section.body.append_child(table)
# Here we could call EnsureMinimum to create the rows and cells for us. This method is used
# to ensure that the specified node is valid. In this case, a valid table should have at least one Row and one cell.
# Instead, we will handle creating the row and table ourselves.
# This would be the best way to do this if we were creating a table inside an algorithm.
row = aw.tables.Row(doc)
row.row_format.allow_break_across_pages = True
table.append_child(row)
# We can now apply any auto fit settings.
table.auto_fit(aw.tables.AutoFitBehavior.FIXED_COLUMN_WIDTHS)
cell = aw.tables.Cell(doc)
cell.cell_format.shading.background_pattern_color = drawing.Color.light_blue
cell.cell_format.width = 80
cell.append_child(aw.Paragraph(doc))
cell.first_paragraph.append_child(aw.Run(doc, "Row 1, Cell 1 Text"))
row.append_child(cell)
# We would then repeat the process for the other cells and rows in the table.
# We can also speed things up by cloning existing cells and rows.
row.append_child(cell.clone(False))
row.last_cell.append_child(aw.Paragraph(doc))
row.last_cell.first_paragraph.append_child(aw.Run(doc, "Row 1, Cell 2 Text"))
doc.save(ARTIFACTS_DIR + "WorkingWithTables.insert_table_directly.docx")

##Создайте таблицу из HTML

Aspose.Words поддерживает вставку содержимого в документ из источника HTML с использованием метода InsertHtml. Входными данными могут быть полная страница HTML или только частичный фрагмент.

Используя метод InsertHtml, пользователи могут вставлять таблицы в документ с помощью тегов таблиц, таких как <table>, <tr>, <td>.

В следующем примере кода показано, как вставить таблицу в документ из строки, содержащей теги HTML:

# 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)
# Note that AutoFitSettings does not apply to tables inserted from HTML.
builder.insert_html("<table>" +
"<tr>" +
"<td>Row 1, Cell 1</td>" +
"<td>Row 1, Cell 2</td>" +
"</tr>" +
"<tr>" +
"<td>Row 2, Cell 2</td>" +
"<td>Row 2, Cell 2</td>" +
"</tr>" +
"</table>")
doc.save(ARTIFACTS_DIR + "WorkingWithTables.insert_table_from_html.docx")

Вставьте копию существующей таблицы

Часто возникает необходимость создать таблицу на основе уже существующей таблицы в документе. Самый простой способ скопировать таблицу с сохранением всего форматирования - это клонировать узел таблицы, используя метод Clone.

Тот же метод можно использовать для добавления копий существующей строки или ячейки в таблицу.

В следующем примере кода показано, как дублировать таблицу с помощью конструкторов узлов:

# 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()
# Clone the table and insert it into the document after the original.
table_clone = table.clone(True).as_table()
table.parent_node.insert_after(table_clone, table)
# Insert an empty paragraph between the two tables,
# or else they will be combined into one upon saving this has to do with document validation.
table.parent_node.insert_after(aw.Paragraph(doc), table)
doc.save(ARTIFACTS_DIR + "WorkingWithTables.clone_complete_table.docx")

В следующем примере кода показано, как клонировать последнюю строку таблицы и добавить ее в таблицу:

# 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()
cloned_row = table.last_row.clone(True).as_row()
# Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into.
for cell in cloned_row.cells:
cell = cell.as_cell()
cell.remove_all_children()
table.append_child(cloned_row)
doc.save(ARTIFACTS_DIR + "WorkingWithTables.clone_last_row.docx")

Если вы хотите создать таблицы в документе, которые динамически увеличиваются с каждой записью из вашего источника данных, то описанный выше метод не рекомендуется. Вместо этого желаемый результат проще получить, используя Mail merge с регионами.

Сравните способы создания таблицы

Aspose.Words предоставляет несколько методов для создания новых таблиц в документе. Каждый метод имеет свои преимущества и недостатки, поэтому выбор того, какой из них использовать, часто зависит от конкретной ситуации.

Давайте подробнее рассмотрим эти способы создания таблиц и сравним их плюсы и минусы:

Метод Преимущества Недостатки
Через DocumentBuilder Стандартный метод вставки таблиц и другого содержимого документа Иногда бывает сложно создать множество разновидностей таблиц одновременно с помощью одного и того же экземпляра конструктора
Через DOM Лучше вписывается в окружающий код, который создает и вставляет узлы непосредственно в DOM без использования DocumentBuilder Таблица создается “пустой”: перед выполнением большинства операций вы должны вызвать EnsureMinimum, чтобы создать все отсутствующие дочерние узлы
Из HTML Можно создать новую таблицу из источника HTML, используя такие теги, как <table>, <tr>, <td> Не все возможные форматы таблиц Microsoft Word могут быть применены к HTML
Клонирование существующей таблицы Вы можете создать копию существующей таблицы, сохранив все форматирование строк и ячеек Соответствующие дочерние узлы должны быть удалены, прежде чем таблица будет готова к использованию