Python Forum
How to create a table with different sizes of columns in MS word
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create a table with different sizes of columns in MS word
#1
Hi,
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 size. I need a help so that the columns sizes 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")
Reply


Messages In This Thread
How to create a table with different sizes of columns in MS word - by pepe - Dec-01-2023, 01:55 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create Choices from .ods file columns cspower 3 652 Dec-28-2023, 09:59 PM
Last Post: deanhystad
  Create csv file with 4 columns for process mining thomaskissas33 3 802 Nov-06-2023, 09:36 PM
Last Post: deanhystad
Thumbs Up Convert word into pdf and copy table to outlook body in a prescribed format email2kmahe 1 797 Sep-22-2023, 02:33 PM
Last Post: carecavoador
  Printing effect sizes for variables in an anova eyavuz21 2 1,013 Feb-01-2023, 02:12 PM
Last Post: eyavuz21
  Output difference from 2 lists of different sizes with words gracenz 5 1,377 Sep-02-2022, 05:09 PM
Last Post: Larz60+
  group by create pivot table python dawid294 1 1,323 Jun-22-2022, 06:13 PM
Last Post: Larz60+
  Sum the values in a pandas pivot table specific columns klllmmm 1 4,698 Nov-19-2021, 04:43 PM
Last Post: klllmmm
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,556 Aug-12-2021, 04:25 PM
Last Post: palladium
  SaltStack: MySQL returner save less data into Database table columns xtc14 2 2,213 Jul-02-2021, 02:19 PM
Last Post: xtc14
  Create SQLite columns from a list or tuple? snakes 6 8,823 May-04-2021, 12:06 PM
Last Post: snakes

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020