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

openpyxl v3.1.1中如何创建包含多单元格区域的条形图?

用openpyxl v3.1.1创建包含不连续数据区域的条形图

问题背景

在使用openpyxl v3.1.1创建条形图时,多数教程仅展示单块连续单元格区域的用法,示例代码如下:

chart1 = BarChart()
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)  # Y data
cats = Reference(ws, min_col=1, min_row=2, max_row=7) # X data
chart1.add_data(data, titles_from_data=True)
# or series_2 = Series(data_dec, title=f"Title") when Title not the first row
# chart1.append(series_2)
chart1.set_categories(cats)
ws.add_chart(chart1, "A10")  # draw chart

但实际场景中需要选取多块不连续的单元格区域(类似Excel中按住Ctrl多选),比如基于如下表格中的2010年1月和2011年1月数据创建条形图:

Data-1Data-2
2010-Jan-10.1
2010-Jan-20.2
2010-Jan-10.3
2010-Feb-10.4
2010-Feb-20.5
2010-Feb-30.6
2011-Jan-10.7
2011-Jan-20.8
2011-Jan-30.9

在Excel中可通过按住Ctrl选中对应区域生成类似=test_1!$A$2:$A$4;test_1!$A$8:$A$10的引用,但openpyxl中没有直接合并多个Reference的方法,这一需求是否可行?

解决方案

可行。openpyxl支持通过手动创建Series对象并传入多个Reference的列表来实现不连续区域的引用,具体实现如下:

示例代码

from openpyxl import load_workbook
from openpyxl.chart import BarChart, Series, Reference

# 加载目标工作簿和工作表
wb = load_workbook("your_file.xlsx")
ws = wb.active

# 定义不连续的数据区域(Y轴:2010-Jan、2011-Jan的Data-2列)
data_ref1 = Reference(ws, min_col=2, min_row=2, max_row=4)
data_ref2 = Reference(ws, min_col=2, min_row=8, max_row=10)

# 定义不连续的分类区域(X轴:对应日期的Data-1列)
cats_ref1 = Reference(ws, min_col=1, min_row=2, max_row=4)
cats_ref2 = Reference(ws, min_col=1, min_row=8, max_row=10)

# 创建条形图实例
chart = BarChart()

# 创建数据系列,传入多个不连续区域的Reference列表
series = Series(values=[data_ref1, data_ref2], title="月度数据")
chart.append(series)

# 设置分类轴,传入多个不连续分类区域的Reference列表
chart.set_categories([cats_ref1, cats_ref2])

# 将图表插入工作表指定位置
ws.add_chart(chart, "A12")

# 保存结果
wb.save("result.xlsx")

关键说明

  • 若需要多个独立的数据系列,可创建多个Series对象并分别append到图表中
  • 需确保每个Reference的行列范围精准对应目标不连续区域
  • 该方式完全模拟Excel中按住Ctrl多选区域的逻辑,生成的图表效果与手动操作Excel一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:57:23