Introdução e criação de tabelas

Aspose.Words permite aos usuários criar tabelas em um documento do zero e fornece vários métodos diferentes para fazer isso. Este artigo apresenta detalhes sobre como adicionar tabelas formatadas ao seu documento usando cada método, bem como uma comparação de cada método no final do artigo.

Estilos de tabela padrão

A tabela recém-criada recebe valores padrão semelhantes aos usados em Microsoft Word:

Propriedade da tabela Padrão em 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

Crie uma tabela com DocumentBuilder

No Aspose.Words, os usuários podem criar uma tabela em um documento usando o DocumentBuilder. O algoritmo básico para criar uma tabela é o seguinte:

  1. Inicie a tabela com StartTable
  2. Adicione uma célula à tabela usando InsertCell – isso inicia automaticamente uma nova linha
  3. Opcionalmente, use a propriedade CellFormat para especificar a formatação da célula
  4. Insira o conteúdo da célula usando os métodos DocumentBuilder apropriados, como Writeln, InsertImage e outros
  5. Repita as etapas 2 a 4 até que a linha esteja completa
  6. Chame EndRow para encerrar a linha atual
  7. Opcionalmente, use a propriedade RowFormat para especificar a formatação de linha
  8. Repita as etapas 2 a 7 até que a tabela esteja completa
  9. Ligue para o EndTable para terminar de construir a mesa

O processo de criação de uma tabela pode ser visto claramente na imagem a seguir:

processo de criação de tabela

O exemplo de código a seguir mostra como criar uma tabela simples usando DocumentBuilder com formatação padrão:

# 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")

O exemplo de código a seguir mostra como criar uma tabela formatada usando 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")

O exemplo de código a seguir mostra como inserir uma tabela aninhada usando 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

Crie uma tabela via DOM (Document Object Model)

Você pode inserir tabelas diretamente no DOM adicionando um novo nó Table em uma posição específica.

Observe que imediatamente após a criação do nó da tabela, a própria tabela estará completamente vazia, ou seja, ainda não contém linhas e células. Para inserir linhas e células em uma tabela, adicione os nós filhos Row e Cell apropriados ao DOM.

O exemplo de código a seguir mostra como construir uma nova tabela do zero adicionando os nós filhos apropriados à árvore do documento:

# 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 uma tabela de HTML

Aspose.Words suporta a inserção de conteúdo em um documento a partir de uma fonte HTML usando o método InsertHtml. A entrada pode ser uma página HTML completa ou apenas um trecho parcial.

Usando o método InsertHtml, os usuários podem inserir tabelas no documento por meio de tags de tabela como <table>, <tr>, <td>.

O exemplo de código a seguir mostra como inserir uma tabela em um documento a partir de uma string contendo tags 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")

Insira uma cópia de uma tabela existente

Muitas vezes você precisa criar uma tabela com base em uma tabela já existente em um documento. A maneira mais fácil de duplicar uma tabela mantendo toda a formatação é clonar o nó Tabela usando o método Clone.

A mesma técnica pode ser usada para adicionar cópias de uma linha ou célula existente a uma tabela.

O exemplo de código a seguir mostra como duplicar uma tabela usando construtores de nó:

# 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")

O exemplo de código a seguir mostra como clonar a última linha de uma tabela e anexá-la à tabela:

# 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")

Se você deseja criar tabelas em um documento que cresçam dinamicamente com cada registro de sua fonte de dados, o método acima não é recomendado. Em vez disso, o resultado desejado é alcançado mais facilmente usando Mail merge com regiões.

Compare maneiras de criar uma tabela

Aspose.Words fornece vários métodos para criar novas tabelas em um documento. Cada método tem suas próprias vantagens e desvantagens, portanto a escolha de qual usar geralmente depende da situação específica.

Vamos dar uma olhada nessas formas de criar tabelas e comparar seus prós e contras:

Método Vantagens Desvantagens
Através do DocumentBuilder O método padrão para inserir tabelas e outros conteúdos de documentos Às vezes é difícil criar muitas variedades de tabelas ao mesmo tempo com a mesma instância do construtor
Via DOM Adapta-se melhor ao código circundante que cria e insere nós diretamente no DOM sem usar um DocumentBuilder A tabela é criada “vazia”: antes de executar a maioria das operações, você deve chamar EnsureMinimum para criar quaisquer nós filhos ausentes
Do HTML Pode criar uma nova tabela a partir de fonte HTML usando tags como <table>, <tr>, <td> Nem todos os formatos de tabela Microsoft Word possíveis podem ser aplicados ao HTML
Clonando uma tabela existente Você pode criar uma cópia de uma tabela existente, mantendo toda a formatação de linhas e células Os nós filhos apropriados devem ser removidos antes que a tabela esteja pronta para uso