create tables in word documents using python

Tables are commonly used in Word documents to organize information in a grid-like structure. They allow you to summarize the information in the form of rows and columns. In this article, you will learn how to create a table in Word documents programmatically using Python. Moreover, the article will cover how to create nested tables or clone an existing table in Word documents.

Python Library to Create Tables in Word Documents

To work with tables in Word documents, we will use Aspose.Words for Python. The library is designed to create and manipulate Word documents dynamically from within the Python applications. You can install the library from PyPI using the following pip command.

pip install aspose-words

Create a Table in a Word Document in Python

The following are the steps to create a table in a Word DOCX document using Python.

  • Create an object of Document class.
  • Create an object of DocumentBuilder class.
  • Start a table using DocumentBuilder.start_table() method and get reference of the table in an object.
  • Insert a cell using DocumentBuilder.insert_cell() method.
  • Set formatting of the cell using DocumentBuilder.cell_format property.
  • Set auto fit using auto_fit(aw.tables.AutoFitBehavior.FIXED_COLUMN_WIDTHS) method.
  • Set alignment of the cell.
  • Insert text into cell using DocumentBuilder.write() method.
  • Repeat inserting cells and text into cells as required.
  • End a row when you complete inserting cells.
  • End table when you have inserted all the rows.
  • Save the Word document using Document.save() method.

The following code sample shows how to create a table in DOCX documents using Python.

import aspose.words as aw
# Create a new Word document.
doc = aw.Document()
# Create document builder.
builder = aw.DocumentBuilder(doc)
# Start the table.
table = builder.start_table()
# Insert cell.
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
# Set alignment and font settings.
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.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()
# End table.
builder.end_table()
# Save the document.
doc.save("table_formatted.docx")
view raw create-table.py hosted with ❤ by GitHub

The following is the screenshot of the table we have created using the code sample above.

Table in a Word DOCX Document

Table in a Word DOCX Document

Create a Nested Table in a Word Document in Python

Aspose.Words for Python also allows you to create a nested table seamlessly. In other words, you can create a new table within a cell of the table. The following are the steps to create a nested table in a Word DOCX file.

  • Create an object of Document class.
  • Create an object of DocumentBuilder class.
  • Start a table using DocumentBuilder.start_table() method and get reference of the table in an object.
  • Insert a cell using DocumentBuilder.insert_cell() method and get reference of the cell in a object.
  • Insert text into cell using DocumentBuilder.write() method.
  • Repeat inserting cells and text into cells as required.
  • End table when you have inserted all the rows.
  • Move control inside the desired cell usng DocumentBuilder.move_to(Cell.first_paragraph) method.
  • Create another table by inserting cells and end the table when done.
  • Save the Word document using Document.save() method.

The following code sample shows how to create a nested table in a DOCX document using Python.

import aspose.words as aw
# Create a new Word document.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# Insert cell.
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()
# Save the document.
doc.save("table_nested.docx")

The following is the output of the code sample above.

Nested Table in a Word Document

Nested Table in a Word Document

Clone an Existing Table in a Word Document in Python

You can also clone an existing table in a Word document. The following are the steps to perform this operation.

  • Load the document using Document class.
  • Get reference of the table in an object using Document.get_child(NodeType.TABLE, int, boolean).as_table() method.
  • Call clone(True).as_table() method using the table’s object and get reference of the cloned table in another object.
  • Insert cloned table using Table.parent_node.insert_after() method.
  • Insert an empty paragraph between tables using Table.parent_node.insert_after(Paragraph(Document), Table) method.
  • Save the Word document using Document.save() method.

The following code sample shows how to clone a table in a Word DOCX document using Python.

import aspose.words as aw
# Load the Word document.
doc = aw.Document("table_formatted.docx")
# Get reference of the desired table.
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table()
# Clone the table and insert it into the document after the original table.
tableClone = table.clone(True).as_table()
table.parent_node.insert_after(tableClone, table)
# Insert an empty paragraph between the two tables,
# or else they will be combined into one upon saving.
table.parent_node.insert_after(aw.Paragraph(doc), table)
# Save the document.
doc.save("table_clone.docx")
view raw clone-table.py hosted with ❤ by GitHub

The following screenshot shows the cloned table in a Word document.

Cloned Table in a Word Document

Cloned Table in a Word Document

Get a Free API License

You can get a temporary license to use Aspose.Words for Python without evaluation limitations.

Conclusion

In this article, you have learned how to create tables in Word documents using Python. Moreover, you have seen how to create nested tables or clone the existing tables in Word documents dynamically. Besides, you can visit the documentation of Aspose.Words for Python to explore other features. In case of any questions, feel free to let us know via our forum.

See Also

Info: If you ever need to get a Word document from a PowerPoint presentation, you can use Aspose Presentation to Word Document converter.