I have been using Openpyxl to transfer pandas dataframes to an Excel file. I have to work utilising a template file given to me by work.
Because I cannot modify much in the 'printable' sheets, I created a worksheet at the end of the workbook where I added all of my dataframes. Now I must plot them and put the various charts in different sheets.
My question is, can I use openpyxl methods to create charts on sheets that are not active? All of the data/labels for the charts are on one sheet, and I want to make the graphs for different sheets. I have searched all of the documentation and this site and cannot find the answer.
An alternative question is, can I copy charts from one sheet to another within the same file? and if so, how can I do it?
Thanks!
You can create charts on non-active sheets. Instead of using active
you can use fixed references to each sheet, eg
wb = Workbook()
ws_data = wb['Data']
I always use worksheets like this ( Explicit is better than implicit
).
Example:
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series
wb = Workbook()
wb.create_sheet('Data')
ws_data = wb['Data']
for i in range(10):
ws_data.append([i])
sheetlist = ['Test1', 'Test2', 'Test3']
for w in sheetlist:
wb.create_sheet(w)
for s in sheetlist:
values = Reference(ws_data, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)
ws = wb[s]
ws.add_chart(chart, "B5")
wb.save("SampleChart.xlsx")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.