python - Openpyxl 图表位置的 For 循环

标签 python excel charts openpyxl

我正在尝试创建一个 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对象和一个string细胞位置。打印值(图表、图表位置)时,您应该会看到 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 个图表。

希望这有帮助。

enter image description here

关于python - Openpyxl 图表位置的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45173780/

相关文章:

ASP.NET 4.0 图表 - 当数据绑定(bind)查询未返回结果时,如何在图表区域中显示解释性消息?

python - GAE Python : Static Files not loading in localhost,,但当应用程序部署到 appspot 时加载完全正常

python - 如何从 python 调用 C 函数?

python - Spark(pyspark)中的决策树模型如何可视化?

Python-MySQLdb问题: wrong ELF class: ELFCLASS32

excel - 如果值是一定长度,如何在Excel中的值的开头添加0

输入数据时 Excel 卡住

javascript - 是否可以在plotly.js箱形图上叠加标记?

javascript - 谷歌折线图 : add a graph of the sum of the readings of other graphs

excel - 范围名称中的 VBA、& 符号和循环