python - 用于 openpyxl 多个图表创建的 for 循环
问题描述
我正在尝试创建一个for
循环以一次在 openpyxl 中创建多个折线图。数组中的某些索引将是图表从中提取数据的数据的书挡。这在openpyxl中可能吗?
我在 excel 电子表格中的数据如下所示:
1 Time Battery Voltage
2 2019-06-05 00:00:00 45
3 2019-06-05 00:01:50 49
4 2019-06-05 00:02:30 51
5 2019-06-05 00:04:58 34
...
import os
import openpyxl
from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference, Series
from openpyxl.chart.axis import DateAxis
from datetime import date, datetime, timedelta, time
os.chdir('C:\\Users\user\test')
wb = openpyxl.load_workbook('log.xlsx')
sheet = wb['sheet2']
ws2 = wb['sheet2']
graphIntervals = [0,50,51,100,101,150] # filled with tuples of two integers,
# representing the top-left and bottom right of the rectangular
# selection of cells containing chart data I'm trying to graph
starts = graphIntervals[::2]
ends = graphIntervals[1::2]
for i in graphIntervals:
c[i] = LineChart()
c[i].title = "Chart Title"
c[i].style = 12
c[i].y_axis.crossAx = 500
c[i].x_axis = DateAxis(crossAx=100)
c[i].x_axis.number_format = 'd-HH-MM-SS'
c[i].x_axis.majorTimeUnit = "days"
c[i].y_axis.title = "Battery Voltage"
c[i].x_axis.title = "Time"
data = Reference(ws2, min_col=2, min_row=starts, max_col=2, max_row=ends)
c[i].add_data(data, titles_from_data=True)
dates = Reference(ws2, min_col=1, min_row=starts, max_row=ends)
c[i].set_categories(dates)
s[i] = c[i].series[0]
s[i].graphicalProperties.line.solidFill = "BE4B48"
s[i].graphicalProperties.line.width = 25000 # width in EMUs.
s[i].smooth = True # Make the line smooth
ws2.add_chart(c[i], "C[i+15]") # +15 for spacing
wb.save('log.xlsx')
理想情况下,我最终会制作(尽管 graphIntervals/2 中有许多值)图表。
我知道我需要合并zip()
到我的data
变量中,否则它无法继续使用下一组值来创建电子表格。我认为它会像zip(starts, ends)
但我不确定。
通过openpyxl可以实现这些吗?虽然我还没有找到,但有人有我可以参考的例子吗?
解决方案
遵循评论中的建议。这是在 for 循环中调用的函数:
for i in range(0, len(graphIntervals), 2):
min_row = graphIntervals[i] + 1
max_row = graphIntervals[i+1] + 1
# skip headers on first row
if min_row == 1:
min_row = 2
dates = chart.Reference(ws2, min_col=1, min_row=min_row, max_row=max_row)
vBat = chart.Reference(ws2, min_col=2, min_row=min_row, max_col=2, max_row=max_row)
qBat = chart.Reference(ws2, min_col=3, min_row=min_row, max_col=3, max_row=max_row)
推荐阅读
- powershell - Powershell 脚本 - 仅以管理员身份运行某些命令,其余脚本以非管理员身份运行
- c# - 在 C# 中合并两个标签 ID 相同的 XML 文件
- openshift - Pod 级路由限制
- python - 如何使用 apply() 函数将字符串列转换为日期类型
- mongodb - 无法为 sharded MongoDB 集群的配置服务器启动副本集
- python - 有没有办法将操作设置为布尔值,然后创建一个 if 语句以在该操作完成时执行某些操作?
- jmeter - 如何在jmeter中运行选择性线程组
- python - 如何使用 Librosa 获得音频的音高?(不是二维数组,但与可丽饼类似)
- c# - 自定义消息编码器 WCF - 无效签名
- azure-servicebus-topics - 即使我的 python 代码正在等待服务总线订阅上的消息,ACI 的计费是否会继续发生?