openpyxl如何更改图表标题和y轴标题的字体大小?

6

我目前正在努力更改Y轴标题和图表标题的字体。

我尝试创建字体设置并将其应用于标题,但毫无进展。

new_chart.y_axis.title = chart_dict['y_title']
ft = Font(name='Calibri',
          size=11,
          bold = False,
          italic = False,
          vertAlign = None,
          underline = 'none',
          strike = False,
          color = 'FF000000')

new_chart.y_axis.title.font = ft

有没有简单的设置方式 - 比如:

chart.y_axis.title.some_size_attrib = 12

我在错误的方向上吗?

这并不是一件容易的事情。请参考openpyxl邮件列表上的各种讨论。 - Charlie Clark
4个回答

7

我希望这不会耽误你太久。经过大量研究,我找到了一种使用 Openpyxl 更改图表段落字体及其大小的方法。

字体大小定义为 sz=1500,表示通常的 15 号字体。根据此逻辑,1200 表示 12 号字体。最小值为 100,最大值为 400000。

from openpyxl.chart.text import RichText
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, Font    

font_test = Font(typeface='Calibri')
cp = CharacterProperties(latin=font_test, sz=1500)
chart.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])

1
非常感谢!经过漫长的搜索,终于找到了这个解决方案! :D - jkhadka

3
在我的情况下,那个并没有正常工作。 最终我使用的是:
from openpyxl.drawing.text import CharacterProperties

cp = CharacterProperties(sz=1100)  # Where size goes from 100 till 40000
mygraph.x_axis.title.tx.rich.p[0].r.rPr = cp

2

在我的情况下,这两个答案都没有起作用,所以我做了以下操作:

from openpyxl.drawing.text import CharacterProperties, Paragraph, ParagraphProperties, RegularTextRun

cp = CharacterProperties(sz=1200)
xtStr = u"X-axis Title"
ytStr = u"Y-axis Title"
myChart.x_axis.title = ""
myChart.y_axis.title = ""
xPara = [Paragraph(pPr=ParagraphProperties(defRPr=cp), r=RegularTextRun(t=s)) for s in xtStr.split("\n")]
yPara = [Paragraph(pPr=ParagraphProperties(defRPr=cp), r=RegularTextRun(t=s)) for s in ytStr.split("\n")]
myChart.x_axis.title.tx.rich.paragraphs = xPara
myChart.y_axis.title.tx.rich.paragraphs = yPara

0
这是一个代码片段,用于更改图表标题的大小。
from openpyxl.drawing.text import (
    ParagraphProperties,
    CharacterProperties,
)

def set_chart_title_size(chart, size=1400):
    paraprops = ParagraphProperties()
    paraprops.defRPr = CharacterProperties(sz=size)

    for para in chart.title.tx.rich.paragraphs:
        para.pPr=paraprops 

set_chart_title_size(chart, size=1400)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接