为什么在openpyxl中更改系列标题会更改对系列数据的引用?

问题描述

我正在开发一个程序,该程序可以读取CSV文件,分析其中的数据并生成带有控制图的Excel工作簿。该程序总体上可以正常运行,但是我的一张图表遇到了一个奇怪的问题。

一个图表引用了电子表格中的三个单元格,以获取一系列标题一个值(重复两次)以获取规格上限。它还引用了两个单元格,以使该系列在图表上可见。当使用数据标题来绘制系列时,它会正确生成一个包含两条数据单元格的水平线图表,如下所示:

openpyxl chart with series title from data

但是,当系列中使用自定义标题时,图表将丢失第一个数据单元格引用,而是使用零值:

openpyxl chart with custom series title and broken series

虽然我可以更改数据引用以解决此问题,但我想知道为什么首先会发生此问题。搜索Stack Overflow和openpyxl文档没有发现任何看起来相关的东西。更改应为外观图表功能内容也会导致显示的数据也发生更改,这很奇怪。

包括了Python 3.8.2和openpyxl 3.0.3的自包含代码,这些代码在工作簿中重现了此问题。只需将title_from_data = True替换为title = 'Maximum',即可生成不正确的图表。

import openpyxl as  pyxl
from openpyxl.chart import (
    ScatterChart,Reference,Series,)

# Create workbook and fill with relevant data
result_book = pyxl.Workbook()
plot_sheet = result_book['Sheet']
result_book.create_sheet('Sheet3')
limits = result_book['Sheet3']
limits['C2'].value = 'Difference Limit'
limits['C3'].value = 0.35
limits['C4'].value = 0.35
limits['B7'].value = 'Start row'
limits['C7'].value = 'End row'
limits['B8'].value = 0
limits['C8'].value = 968

# Define row and column values for referencing
num_row_in_data = limits['C8'].value
limit_start_row = 3
data_end_row = num_row_in_data + 3
limit_xval_row = 8

# Setup plot and define maximum values for X and Y axes
plot1 = ScatterChart()
plot1.title = 'Plot 1'
usl = limits['C'+str(limit_start_row)].value
plot1.x_axis.scaling.min = 0
plot1.y_axis.scaling.min = 0
plot1.x_axis.scaling.max = num_row_in_data
plot1.y_axis.scaling.max = usl + 0.05

# Reference cells and turn values into a series
usl_val = Reference(limits,min_col = 3,min_row = 2,max_col = 3,max_row = 4)
limit_xval = Reference(limits,min_col = 2,min_row = limit_xval_row,max_row = limit_xval_row)

usl_series = Series(usl_val,limit_xval,title_from_data = True)
plot1.series.append(usl_series)
plot_sheet.add_chart(plot1,'A1')

# Save and close workbook
book_name = 'workbook.xlsx'
result_book.save(book_name)
result_book.close

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)