import openpyxl
from openpyxl.chart import LineChart, Reference
# 创建一个工作簿
workbook = openpyxl.Workbook()
sheet = workbook.active
# 添加数据到工作表
data = [
["年份", "销售额"],
[2010, 100],
[2011, 150],
[2012, 200],
[2013, 250],
[2014, 300],
]
for row in data:
sheet.append(row)
# 创建折线图
chart = LineChart()
data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)
categories = Reference(sheet, min_col=1, min_row=2, max_row=6)
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
chart.title = "销售额趋势"
# 将折线图添加到工作表
sheet.add_chart(chart, "E5")
# 保存工作簿
workbook.save("line_chart.xlsx")