简体   繁体   中英

Is it possible to apply a chart template to an Excel chart using openpyxl?

I'm trying to automate the creation of some charts in Excel. They need to be styled to a particular theme.

Using openpyxl, how could I apply a template to a chart? I can't find anything in the docs, or by searching the Github repo. Have I missed anything?

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

from openpyxl.chart import BarChart, Reference, Series
values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)

### chart.apply_template("template_loc.crtx") <-- What can go here?

ws.add_chart(chart, "E15")
wb.save("SampleChart.xlsx")

As far as I can see, it is not possible to load an *.crtx chart template file and apply it to an existing chart. But you can try to recreate the style manually using graphicalProperties :

from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series
from openpyxl.chart.marker import DataPoint
from openpyxl.drawing.fill import PatternFillProperties, ColorChoice

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


values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)

# set a pattern for the whole series
series = chart.series[0]
fill =  PatternFillProperties(prst="pct5")
fill.foreground = ColorChoice(prstClr="red")
fill.background = ColorChoice(prstClr="green")
series.graphicalProperties.pattFill = fill

# set a pattern for a 6th data point (0-indexed)
pt = DataPoint(idx=5)
pt.graphicalProperties.pattFill = PatternFillProperties(prst="ltHorz")
series.dPt.append(pt)

ws.add_chart(chart, "E15")
wb.save("SampleChart.xlsx")

This creates:

样式条形图

It might take some fiddling to exactly recreate the theme you need.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM