JanP
JanP

Reputation: 1

how to set color to value in python-docx table?

Using python-docx my code produces a Word file. In this file I make a table. First kolom is named: onderwerp. Values in this column are subjects. The names of the other columns are the 12 months. In each column (besides the first column: onderwerp) are values. I want to color these values. Is the value < 8: red. Is the value < 9 but > 8: orange. >= 9: green. This is my first docx code and after trying for a lot of hours I would like to ask for help

This is my code:

table = document.add_table(rows=len(df_opmerkingen) + 1, cols=len(df_opmerkingen.columns))  # +1 for header row
        table.autofit = True
        table.style = 'Table Grid'  # Apply a pre-defined table style
        
        # Set headers for the table
        hdr_cells = table.rows[0].cells
        for col_idx, col_name in enumerate(df_opmerkingen.columns):
            hdr_cells[col_idx].text = col_name
        
        # Fill the table with data from the DataFrame
        for row_idx in range(len(df_opmerkingen)):
            row_cells = table.rows[row_idx + 1].cells  # Skip header row
            for col_idx in range(len(df_opmerkingen.columns)):
                row_cells[col_idx].text = str(df_opmerkingen.iloc[row_idx, col_idx])
        
        # Center the table on the page
        table.alignment = WD_TABLE_ALIGNMENT.CENTER
        
        # Optional: Adjust cell font size
        for row in table.rows:
            for cell in row.cells:
                paragraphs = cell.paragraphs
                for paragraph in paragraphs:
                    for run in paragraph.runs:
                        font = run.font
                        font.size = Pt(11)

I tried to build an if else. But (not smart thinking from my side) obviously using Pandas en Python code does not work because the type value is different.

Asked Gemini a few suggestions, but that did not work...

Upvotes: 0

Views: 37

Answers (1)

Austin
Austin

Reputation: 51

This is some revised code to do what you want:

import docx
import pandas as pd
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.shared import OxmlElement, qn

df_opmerkingen = pd.read_excel('Colours.xlsx', header=0)
file = 'Colours.docx'
document = docx.Document(file)
table = document.add_table(rows=len(df_opmerkingen) + 1, cols=len(df_opmerkingen.columns))  # +1 for header row
table.autofit = True
table.style = 'Normal Table'  # Apply a pre-defined table style

# Set headers for the table
hdr_cells = table.rows[0].cells
for col_idx, col_name in enumerate(df_opmerkingen.columns):
    hdr_cells[col_idx].text = str(col_name)

# Fill the table with data from the DataFrame
for row_idx in range(len(df_opmerkingen)):
    row_cells = table.rows[row_idx + 1].cells  # Skip header row
    for col_idx in range(len(df_opmerkingen.columns)):
        value = df_opmerkingen.iloc[row_idx, col_idx]
        row_cells[col_idx].text = str(value)
        if row_cells[col_idx].text.replace(".", "").isnumeric():
             if value < 8:
                colour = '#FF0000'  # red
            elif value < 9:
                colour = '#FFA500'  # amber
            else:
                colour = '#90EE90'  # green
            cell = table.cell(row_idx + 1, col_idx)
            tcPr = cell._tc.get_or_add_tcPr()
            tcVAlign = OxmlElement('w:shd')
            tcVAlign.set(qn('w:fill'), colour)
            tcPr.append(tcVAlign)

# Center the table on the page
table.alignment = WD_TABLE_ALIGNMENT.CENTER

# Optional: Adjust cell font size
for row in table.rows:
    for cell in row.cells:
        paragraphs = cell.paragraphs
        for paragraph in paragraphs:
            for run in paragraph.runs:
                font = run.font
document.save(file)

This is the Excel data used to generate the df:

Blockquote

This is the resulting Word document:

Blockquote

Upvotes: 0

Related Questions