下面是使用 Python 的 Openpyxl 包生成的代码和生成的 Excel 图表。
下面也是我希望结果看起来像的图表
如何将以下内容添加到图表中?我用红色圈出了我想添加的图表的特征。
代码
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")
电流输出
所需输出
最佳答案
对于这种效果,您必须准备分析文件的 XML。例如,您可以使用 RichText 对象创建样式标题,这与您使用数据标签的方式非常相似,并且看起来您需要在图表上使用像 chart.dropLines = ChartLines()
这样的下拉线。
因为 openpyxl 几乎直接实现了 OOXML 规范,所以最好的文档是 OOXML 规范。
关于python - 如何使用 Python 和 Openpyxl 向我的 Excel 折线图添加高级样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56638776/