openpyxl多图表创建的for循环

时间:2019-06-25 16:45:17

标签: python excel openpyxl

我正在尝试创建一个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可以做到这一点吗?尽管我还没有找到任何人,但是有人能参考我的例子吗?

1 个答案:

答案 0 :(得分:0)

注释中遵循了建议。这是在for循环中调用的函数:

[[{124} {124}]
 [{124} {124}]]