import openpyxl
from openpyxl.chart import BarChart, Reference
# 创建一个工作簿
workbook = openpyxl.Workbook()
sheet = workbook.active
# 添加数据到工作表
data = [
["产品", "销售额"],
["产品A", 100],
["产品B", 200],
["产品C", 300],
]
for row in data:
sheet.append(row)
# 创建柱状图
chart = BarChart()
data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=4)
categories = Reference(sheet, min_col=1, min_row=2, max_row=4)
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
chart.title = "产品销售额"
# 将柱状图添加到工作表
sheet.add_chart(chart, "E5")
# 保存工作簿
workbook.save("bar_chart.xlsx")
Python+Excel实现柱状图
最新推荐文章于 2024-08-27 16:38:10 发布