You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用OpenPyXL制作带彩色负值的Excel 3D条形图?

解决openpyxl 3D条形图负值条形颜色异常问题

你遇到的问题是openpyxl生成的3D条形图中,负值条形默认显示为黑白色,这是因为每个图表系列(Series)的负值有独立的格式配置项negativeFormat,默认未与正值同步颜色。以下是可行的解决方案:

修改代码要点

遍历图表的所有数据系列,同时设置正值填充色和负值填充色,确保两者一致:

import openpyxl
from openpyxl.chart import (
    Reference,
    Series,
    BarChart3D,
)
from openpyxl.workbook import Workbook  # 补充Workbook的导入

wb = Workbook()
ws = wb.active

rows = [
    (None, 2013, 2014),
    ("Apples", -5, -4),
    ("Oranges", 6, -2),
    ("Pears", -8, 3)
]

for row in rows:
    ws.append(row)

data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=4)
titles = Reference(ws, min_col=1, min_row=2, max_row=4)
chart = BarChart3D()
chart.title = "3D Bar Chart"
chart.style = 2
chart.add_data(data=data, titles_from_data=True)
chart.set_categories(titles)

# 关键:为每个系列同时设置正值和负值的填充色
fill_color = 'FFFF66'
for series in chart.series:
    series.graphicalProperties.solidFill = fill_color
    # 设置负值条形的填充色,与正值保持一致
    series.negativeFormat.graphicalProperties.solidFill = fill_color

ws.add_chart(chart, "E5")
wb.save("bar3d.xlsx")

说明

  • 你之前仅设置了第一个系列(2013)的正值颜色,未处理负值格式,也未覆盖第二个系列(2014)的配置
  • negativeFormat是每个Series的内置属性,专门控制负值数据点的显示样式,直接设置其graphicalProperties.solidFill即可同步颜色
  • 该方案无需修改原始数据,也不需要额外生成临时文件,完全在原代码流程内解决问题

内容的提问来源于stack exchange,提问作者Dynoxic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:48:16