Openpyxl不显示第二张图

时间:2019-06-26 12:31:00

标签: python excel openpyxl

编辑:已解决,下面的答案中的解决方案。

我有一个用openpyxl创建的图形,其中有两个y轴共享一个DateAxis。尽管第一个数据选择显示在图形上,但第二个则没有。图的底部还有一条以前没有的奇怪的灰色线。我认为这只是我在某处缺少的一个小错误,但我看不到哪里。特别是考虑到我已经正确定义了单元格范围。我可能做错了什么?

enter image description here

import openpyxl
from openpyxl import Workbook, chart
from openpyxl.chart import LineChart, Reference, Series
from openpyxl.chart.axis import DateAxis
from datetime import date, datetime, timedelta, time
ws2 = wb['sheet2']
dates = chart.Reference(ws2, min_col=1, min_row=2, max_row=sheet.max_row)
vBat = chart.Reference(ws2, min_col=2, min_row=1, max_col=2, max_row=sheet.max_row)
qBat = chart.Reference(ws2, min_col=3, min_row=1, max_col=3)

c1 = chart.LineChart()
c1.title = "SLA Discharge - 5.5A: V_BAT"
c1.style = 12
c1.x_axis.majorTimeUnit = "days"
c1.x_axis = chart.axis.DateAxis()
c1.x_axis.title = "Time"
c1.x_axis.crosses = "min"
c1.x_axis.majorTickMark = "out"
c1.x_axis.number_format = 'd-HH-MM-SS'
c1.add_data(vBat, titles_from_data=True)
c1.set_categories(dates)
c1.y_axis.title = "Battery Voltage"
c1.y_axis.crossAx = 500
c1.y_axis.majorGridlines = None


c2 = chart.LineChart()
c2.x_axis.axId = 500 # same as c1
c2.add_data(qBat, titles_from_data=True, from_rows=True)
c2.set_categories(dates)
c2.y_axis.axId = 200
c2.y_axis.title = "Qbat Percentage"
c2.y_axis.crossAx = 500

c1.y_axis.crosses = "max"
c1 += c2


s1 = c1.series[0]
s1.graphicalProperties.line.solidFill = "BE4B48"
s1.graphicalProperties.line.width = 25000 # width in EMUs.
s1.smooth = True # Make the line smooth
s2 = c2.series[0]
s2.graphicalProperties.line.solidFill = "48BBBE"
s2.graphicalProperties.line.width = 25000 # width in EMUs.
s2.smooth = True # Make the line smooth
ws2.add_chart(c1, "D5")

足够有趣,

vBat = chart.Reference(ws2, min_col=2, min_row=1, max_col=2, max_row=sheet.max_row)

很好。但是,对qBat执行以下操作:

qBat = chart.Reference(ws2, min_col=3, min_row=1, max_col=3, max_row=sheet.max_row)

“损坏”工作簿并在打开时显示错误消息,并且不打印任何图表。从两行中删除max_row=sheet.max_row会产生一个错误的DateAxis,该日期轴上只有两个点,并且它们都是time列中的前两个值。

1 个答案:

答案 0 :(得分:0)

首先,在c2.add_data(qBat, titles_from_data=True, from_rows=True)中,删除from_rows=True

然后,将qBat更改为:

qBat = chart.Reference(ws2, min_col=3, min_row=1, max_col=3, max_row=sheet.max_row)