Formatting chart data labels in openpyxl

Deadly 提交于 2019-12-09 04:00:32

I got there in the end, via trying to work out how to change the axis labels... this should be extendable to any changes (using either the paragraph properties for fonts etc, or body properties for alignment etc).

from openpyxl.chart import LineChart, Reference, Series
from openpyxl.chart.label import DataLabelList
from openpyxl.chart.text import RichText
#additional imports needed for the solution:
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties

chart1 = LineChart()
# setup and append the first series
values = Reference(dprsheet, min_col=5, min_row=4, max_row=34)
series = Series(values, title="Series 1")
chart1.append(series)
# setup and append the second series
values = Reference(dprsheet, min_col=8, min_row=4, max_row=34)
series = Series(values, title="Series 2")
chart1.append(series)

dates = Reference(dprsheet, min_col=2, min_row=4, max_row=34)
chart1.set_categories(dates)

#create label styling
axis = CharacterProperties(sz=800)
rot = openpyxl.drawing.text.RichTextProperties(vert='vert270')

#set axis label styles
chart1.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=axis), endParaRPr=axis)], bodyPr=rot)
chart1.y_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=axis), endParaRPr=axis)])

#set data labels and styles
s1 = chart1.series[0]
s1.dLbls = DataLabelList() 
s1.dLbls.showVal = True
s1.dLbls.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=axis), endParaRPr=axis)], bodyPr=rot)

Note that chart.dataLabels.dLblPos still does not work (txPr can be amended but not position). The obvious work around requires setting position on each series individually.

Sorry, but I'm afraid you're hitting the limitations of the OOXML specification which isn't always very clear on this stuff. Essentially, at this level openpyxl exposes the XML schema to Python so you're best having a copy of the specification to hand along with a comparable file created by Excel to see what it does.

For an example of the kind of thing that is undocumented: if you want chartlines to have different colour you must have lumOff before lumMod in the relevant part of DrawingML.

We're never going to be able to document all this in openpyxl.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!