用于 Openpyxl 图表位置的循环

For Loop for Openpyxl Chart Position

我正在尝试制作一个 for 循环来遍历图表名称和位置列表,以便使用 openpyxl 更轻松地将图表添加到 excel。这是我到目前为止尝试过的方法。

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

def trysomething():

    letterlist=['B', 'J', 'R', 'Z']
    numlist=[22, 38, 54, 70]
    position=[]
    for k in letterlist:
        for l in numlist:
            pos = k+str(l)
            position.append(pos)

    chartlist=['chart']
    chartnum=[]
    for j in range(1,6):
        chartnum.append(j)

    cha=[]
    for h in chartlist:
        for s in chartnum:
            ch=h+str(s)
            cha.append(ch)

    wb = Workbook()
    ws = wb.active
    for i in range(10):
        ws.append([i])

    values1 = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
    chart1 = BarChart()
    chart1.add_data(values1)

    values2 = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
    chart2 = BarChart()
    chart2.add_data(values2)

    values3 = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
    chart3 = BarChart()
    chart3.add_data(values3)

    values4 = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
    chart4 = BarChart()
    chart4.add_data(values4)

    values5 = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
    chart5 = BarChart()
    chart5.add_data(values5)

    for a, b in zip(iter(cha), iter(position)):
         print(a,b)
         ws.add_chart(str(a), str(b))

     wb.save("SampleChart.xlsx")

trysomething()

当我打印 (a,b) 时,它会输出具有正确图表位置的正确图表,但是,我无法添加图表。

感谢任何帮助!

Workbook().active.add_chart() 接受 Chart object and a string cell position. When printing the values (chart, chart position) you should expect to see an instance of Chart <class 'openpyxl.chart.bar_chart.BarChart'>'string',但您看到 ab 都是 <str>(字符串)对象,因此您的代码将两个 string 对象传递给 .add_chart(),没有 Chart.

你会想做一些事情,比如创建一个 chart_list 并迭代它:

charts_list = [chart1, chart2, chart3, chart4, chart5]

for a, b in zip(iter(charts_list), iter(position)):
     # print(type(a))  # <class 'openpyxl.chart.bar_chart.BarChart'>
     # print(type(b))  # <type 'str'>
     ws.add_chart(a, b)

查看创建的 Excel 文件应该类似于以下内容,包含 5 个图表。

希望这对您有所帮助。