简体   繁体   English

是否可以使用 openpyxl 将图表模板应用于 Excel 图表?

[英]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.我正在尝试在 Excel 中自动创建一些图表。 They need to be styled to a particular theme.它们需要根据特定主题进行样式设置。

Using openpyxl, how could I apply a template to a chart?使用 openpyxl,我如何将模板应用于图表? I can't find anything in the docs, or by searching the Github repo.我在文档中找不到任何内容,或者通过搜索 Github 存储库。 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.据我所知,无法加载*.crtx图表模板文件并将其应用于现有图表。 But you can try to recreate the style manually using graphicalProperties :但是您可以尝试使用graphicsProperties 手动重新创建样式

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.准确地重新创建您需要的主题可能需要一些摆弄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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