如何在 python-docx 表中设置颜色值?

问题描述 投票:0回答:1

使用 python-docx 我的代码生成一个 Word 文件。在这个文件中我制作了一个表格。第一个 kolom 被命名为:onderwerp。此列中的值是主题。其他列的名称是 12 个月。每列(除了第一列:onderwerp)都有值。 我想为这些值着色。值是< 8: red. Is the value < 9 but >8:橙色。 >= 9:绿色。 这是我的第一个 docx 代码,在尝试了很多小时之后,我想寻求帮助

这是我的代码:

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)

我尝试构建一个 if else 。但是(从我的角度来看,这不是聪明的想法)显然使用 Pandas 和 Python 代码是行不通的,因为类型值不同。

向双子座询问了一些建议,但没有效果...

python-docx
1个回答
0
投票

这是一些修改后的代码,可以执行您想要的操作:

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.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)

这是用于生成 df 的 Excel 数据:

Blockquote

这是生成的 Word 文档:

Blockquote

© www.soinside.com 2019 - 2024. All rights reserved.