Python Forum
Openpyxl overwrite Linechart - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Openpyxl overwrite Linechart (/thread-38799.html)



Openpyxl overwrite Linechart - SamLiu - Nov-26-2022

Hi All,
Is there any way to overwrite linechart in excel?It get more chart in excel during running *.Py code. Please refer to attachment file.
If have a way to delete exist chart and then run code once get a new chart, thanks in advance!



import openpyxl
from openpyxl.chart import Reference, LineChart, Series

wb = openpyxl.load_workbook('wb2.xlsx')
sheet = wb.active

# Data for plotting
# Choose all the data from Column 2 to 4
values = Reference(sheet,
                   min_col=2,
                   max_col=10,
                   min_row=1,
                   max_row=38)

# Create object of LineChart class
chart = LineChart()
chart.add_data(values, titles_from_data=True)
# set the title of the chart
chart.title = "Analysis Stock prices"
# set the title of the x-axis
chart.x_axis.title = "Date"

# set the title of the y-axis
chart.y_axis.title = "Stock Value"

# the top-left corner of the chart
# is anchored to cell F2 .
sheet.add_chart(chart,"F2")

# save the file
wb.save("wb2.xlsx")