Hi there,
I have a code to create a table in Microsoft word (see code below). The problem is that once the table is created, it has equal column widths. I need a help so that the columns widths be proportional to the content of each column of the table, but with a certain maximum. For example, with regards to the code I provide below, I want the column of the age column to be smaller than the column of Name and the column of Name be smaller than the column of Occupation and the column of Occupation to remain as it is.
from docx import Document
from docx.shared import Pt
from docx.enum.table import WD_ALIGN_VERTICAL
def create_table(data, headers, filename):
# Create a new Word document
doc = Document()
# Add a table with the given number of rows and columns
rows = len(data) + 1 # Add one for the header row
cols = len(headers)
table = doc.add_table(rows=rows, cols=cols)
# Set the table style (optional)
table.style = 'Table Grid'
# Populate the header row
header_cells = table.rows[0].cells
for col_index, header_text in enumerate(headers):
header_cells[col_index].text = header_text
# Populate the data rows
for row_index, row_data in enumerate(data, start=1):
row_cells = table.rows[row_index].cells
for col_index, cell_value in enumerate(row_data):
row_cells[col_index].text = str(cell_value)
# Set cell formatting (e.g., vertical alignment)
row_cells[col_index].vertical_alignment = WD_ALIGN_VERTICAL.CENTER
# Set column widths based on content
for col_index in range(cols):
max_width = max(len(str(row_data[col_index])) for row_data in data)
# Set a minimum width for columns to avoid being too narrow
min_width = Pt(1.0)
table.columns[col_index].width = max(min_width, Pt(max_width * 1.2)) # Adjust the factor as needed
# Save the Word document
doc.save(filename)
# Example usage:
data = [
["John Doe", 30, "Engineer"],
["Jane Smith", 25, "Construction Designer"],
["Samantha", 25, "Hair worker and assistant to Manager"],
["Bob Johnson", 35, "Manager"]
]
headers = ["Name", "Age", "Occupation"]
create_table(data, headers, "example_table.docx")