首页 > 解决方案 > 如何使用 openpyxl 将数据动态添加到现有图表中

问题描述

当新数据使用openpyxl进入excel时,我正在尝试将数据动态添加到现有折线图中。下面是我尝试过的示例代码但是当遇到其他部分时,图表没有变化。谢谢

from openpyxl import load_workbook
from openpyxl.chart import (LineChart, Reference)

wb = load_workbook("Hello.xlsx")
sheet = wb.active
exists = 0
chart = LineChart()
if exists == 1:
    values = Reference(sheet, min_col=3, min_row=1, max_row=sheet.max_row)
    categories = Reference(sheet, min_col=1, min_row=2, max_row=sheet.max_row,max_col=1)
    chart.add_data(values, titles_from_data=True)
    chart.set_categories(categories)
    chart.title = "sample"
    chart.x_axis.title = "date"
    chart.y_axis.title = "followers"

    sheet.add_chart(chart, "F2")
else:
    values_update = Reference(sheet, min_col=3, min_row=1, max_row=sheet.max_row)
    chart.add_data(values_update)
wb.save("Hello.xlsx")

标签: pythonexcelchartsopenpyxl

解决方案


推荐阅读