如何使用Python的xlsxwriter在条件格式中添加最小/最大值?

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

我正在尝试创建一个具有条件格式的 shmoo 图,其中格式规则知道最小值,并且不会用最小颜色标记表中的最小值,而是知道最小值。例如,在 10x10 的得分表中,规则不应将最低分 80 的单元格标记为红色(例如),但由于它知道最小可能值为 0,因此会将其放置在相应的色阶。 shmoo 图示例以及使用应用程序的预期公式

我在 python 3.12 中使用 xlsxwriter 库

        worksheet.conditional_format(   #condtional formatting 3 color scale, colors in hex
        1,1,len(master_x_axis[i]),len(master_y_axis[i]),
        {
            "type": "3_color_scale",
            "min_color": "#ff6666",
            "mid_color": "#ffff66",
            "max_color": "#8cff66",
            "min_value": 0,
            "max_value": xlsxwriter.utility.xl_rowcol_to_cell(1,len(master_x_axis[i])+2)
        },
    )

我已经尝试了上面的代码,除了“min_value”和“max_value”之外,一切正常,我看不到它反映在Excel文件中。

python excel conditional-formatting xlsxwriter
1个回答
0
投票

该示例几乎可以工作,但需要将

min_type
max_type
参数设置为所需的类型,在本例中可能是“数字”和“公式”。公式范围也应该是绝对的。

类似这样的:

import pandas as pd
from xlsxwriter.utility import xl_rowcol_to_cell


# Create a Pandas dataframe from some data.
df = pd.DataFrame(
    {
        "A": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "B": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "C": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "D": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "E": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "F": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "G": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "H": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "I": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
        "J": [10, 10, 10, 10, 10, 10, 10, 10, 10, 0],
    }
)

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_conditional.xlsx", engine="xlsxwriter")

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name="Sheet1")

# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets["Sheet1"]

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Write the target max value:
worksheet.write(1, max_col + 2, 10)


# Apply a conditional format to the required cell range.
worksheet.conditional_format(1, 1, max_row, max_col,
    {
        "type": "3_color_scale",
        "min_color": "#ff6666",
        "mid_color": "#ffff66",
        "max_color": "#8cff66",

        "min_type": "num",
        "min_value": 0,

        "max_type": "formula",
        "max_value": f"={xl_rowcol_to_cell(1, max_col + 2, row_abs=True, col_abs=True)}",
    },
)

# Close the Pandas Excel writer and output the Excel file.
writer.close()

这给出了以下条件格式:

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.