Введення та створення таблиць
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 |
У таблиці можна ввімкнути, якщо вона щільно позиціонується, або плаваючи, якщо вона може розташовуватися в будь-якому місці на сторінці. За замовчуванням, Aspose.Words завжди створює вбудовані таблиці.
|
Створити таблицю з документобудуванням
У Aspose.Words, Користувачі можуть створити таблицю в документі за допомогою документа DocumentBuilderй Основний алгоритм створення таблиці:
1,1 км Почати таблицю StartTable 2,2 км Додати клітинку до столу за допомогою InsertCell – це автоматично запускає новий ряд 3. У Додатково використовуйте CellFormat властивість вказати форматування комірок 4. У Вставте вміст комірки за допомогою відповідного DocumentBuilder методи, такі як Writeln, InsertImage, та інші 5. Умань Повторюємо кроки 2-4 до завершення ряду 6. Жнівень Дзякуй EndRow до кінця поточного ряду 7. Навігація Додатково використовуйте RowFormat властивість вказати форматування рядків 8. У Повторюємо кроки 2-7 до завершення таблиці 9. Навігація Дзякуй EndTable для завершення будівництва столу
Важливі деталі:
- до StartTable також можна назвати всередині комірки, в якому випадку він запускає створення гніздованого столу в комірці.
- Після виклику InsertCell, Створено нову клітинку, і будь-який вміст, який ви додаєте за допомогою інших методів DocumentBuilder клас буде додано в поточну комірку. Щоб створити нову клітинку на одному ряду, зателефонуйте InsertCell знову.
- Якщо InsertCell після EndRow і кінець ряду, стіл триватиме на новому ряду.
- У EndTable спосіб завершення таблиці слід назвати тільки після виклику EndRowй Дзвінки EndTable переміщує курсор з поточного осередку до положення відразу після столу.
Процес створення таблиці можна чітко побачити в наступному малюнку:
Приклад коду показує, як створити простий стіл за допомогою 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") |
Створити таблицю через DOM (Українська)Document Object Modelй
Ви можете вставляти таблиці безпосередньо в 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") |
##Create з 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") |
Вставте Копію Existing Table
Часто необхідно створити таблицю на основі вже існуючого столу в документі. Найпростіший спосіб дублювати таблицю, зберігаючи всі форматування, щоб клонувати вузол таблиці за допомогою таблиці 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 надає декілька способів створення нових таблиць у документі. Кожен метод має свої переваги і недоліки, тому вибір яких часто залежить від конкретної ситуації.
Давайте розглянемо ці способи створення таблиць і порівняння їх плюсів і мінусів:
Мета | Переваги | Недоліки |
---|---|---|
English, Українська, Français. | Стандартний метод вставки таблиць та іншого вмісту документа | Іноді складно створити безліч сортів столів одночасно з тим же екземпляром будівель |
Про нас DOM | Підходить в краще з навколишнім кодом, який створює і вставляє вершини безпосередньо в DOM без використання DocumentBuilder | Стіл створений “empty”: перед виконанням більшості операцій необхідно викликати EnsureMinimum створити будь-які відсутні дочірні вузли |
Від HTML | Може створити новий стіл з джерела HTML, використовуючи теги, такі як <table> , <tr> , <td> |
Не всі можливі Microsoft Word формати таблиці можна застосувати до HTML |
Покриття існуючого столу | Ви можете створити копію існуючого столу, зберігаючи всі рядки та форматування комірок | Для використання необхідно видалити відповідні дочірні вузли дитини до таблиці |