如何使用Python和Openpyxl将高级样式添加到Excel折线图中

时间:2019-06-17 20:53:17

标签: python excel charts openpyxl

下面是使用Python的Openpyxl软件包生成的代码和生成的Excel图表。
下面也是图表,我希望结果看起来像 如何在图表中添加以下内容?我用红色圈出了要添加的图表的功能。

  1. 从每个数据点延伸到图形X轴的虚线矩形放线。

  2. 带有2种单独的字体/大小的左对齐标题对齐方式(“ Title”设置了1种字体,“ Title2”和“ Title3”设置了单独的字体)

  3. 图形下方的多个浮动文本框(请参见底部的***注1、2、3)

代码

import openpyxl
from openpyxl.chart import LineChart,Reference 
from openpyxl.chart.label import DataLabelList
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, Font    


excel = "Template.xlsx"

excel_file = openpyxl.load_workbook(excel)

Output_Sheet = excel_file.get_sheet_by_name('Sheet1')

excel_file.save("Template2.xlsx")

#Define data
data = Reference(Output_Sheet, min_col = 25, min_row = 5, 
                         max_col = 25, max_row = 15) 

#Define category
categories = Reference(Output_Sheet, min_col = 23, min_row = 5, 
                         max_col = 24, max_row = 15) 
#Initialize
chart = LineChart() 

#add Data
chart.add_data(data) 

#Add category
chart.set_categories(categories)

#Define title
chart.title = " Title \n Title2 \n Title3"

# set the title of the x-axis 

# set the title of the y-axis 
chart.y_axis.title = "Revenue "

#Define chart and font
font_test = Font(typeface='Avenir LT Std 55 Roman')
cp = CharacterProperties(latin=font_test, sz=1500)
chart.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])
chart.y_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])
chart.title.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])

#Size
chart.height = 17.5 # default is 7.5
chart.width = 40 # default is 15

#Remove legend
chart.legend = None

s2 = chart.series[0]
s2.smooth = True # Make the line smooth

#Show Data Label
chart.dataLabels = DataLabelList() 
chart.dataLabels.showVal = True

#Define font and size
font_test = Font(typeface='Avenir LT Std 55 Roman')
cp = CharacterProperties(latin=font_test, sz=750)

chart.dataLabels.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])

#Add Chart
Output_Sheet.add_chart(chart, "B18") 

# save the file 
excel_file.save("Template2.xlsx")

当前输出

enter image description here

所需的输出

enter image description here

1 个答案:

答案 0 :(得分:0)

为此,您必须准备分析文件的XML。例如,您可以使用RichText对象创建样式化的标题,这与处理数据标签的方式非常相似,并且看起来您需要在图表上使用下拉线,例如chart.dropLines = ChartLines()

因为openpyxl几乎直接实现OOXML规范,所以最好的文档就是OOXML规范。