是否可以使用openpyxl更改图表中的大小字体?

时间:2017-09-29 06:05:21

标签: python excel charts openpyxl

我在Windows上使用Python版本2.7和openpyxl版本2.4.0。我需要更改图表中的字体大小(标题/图例中)。可能吗?我在openpyxl文档和在线搜索到处都是,但我找不到任何东西。

我尝试使用

from openpyxl import Workbook
from openpyxl.chart import Reference, Series, LineChart, BarChart
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, Font

chart = BarChart()
chart.type = 'col'
chart.style = 20
chart.y_axis.title = 'Stress, MPa'
data = Reference(ws, min_col=6, min_row=2, max_row=q-1, max_col=7)
cats = Reference(ws, min_col=1, min_row=3, max_row=q-1)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
chart.shape = 4

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

ws.add_chart(chart, "I31")

当我使用它时,我在Excel中有错误('无法显示内容')。但是我的代码没有错误地传递

2 个答案:

答案 0 :(得分:1)

这是更改字体颜色和大小的最短方法

list_rows_3 = []
main_heading = ['Test',' ', 'Group Name', 'Result Status', ' ', 'Count']
m1 = [ font_color(item,20,'000000') for item in main_heading ]
list_rows_3.append(m1)

答案 1 :(得分:0)

是的,这是可能的

>>> from openpyxl.styles import colors
>>> from openpyxl.styles import Font, Color
>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>>
>>> a1 = ws['A1']
>>> d4 = ws['D4']
>>> ft = Font(color=colors.RED)
>>> a1.font = ft
>>> d4.font = ft
>>>
>>> a1.font.italic = True # is not allowed 
>>>
>>> # If you want to change the color of a Font, you need to reassign it::
>>>
>>> a1.font = Font(color=colors.RED, italic=True) # the change only affects A1

来源:openpyxl documentation

相关问题