利用Python创建Excel条形图
创建Excel条形图是学习Python办公自动化的扩展知识,我虽然这么说但是还是属于重要的内容之一。想要通过Python创建Excel图形我们需要用到函数openpyxl里面的相关函数,以下是程序执行代码:
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
wb = Workbook(write_only=True)
ws = wb.create_sheet()
rows = [
('类别', '销售A组', '销售B组'),
('手机', 40, 30),
('平板', 50, 60),
('笔记本', 80, 70),
('外围设备', 20, 10),
]
for row in rows:
ws.append(row)
chart1 = BarChart()
chart1.type = 'col'
chart1.style = 10
chart1.title = '销售统计图'
chart1.y_axis.title = '销量'
chart1.x_axis.title = '商品类别'
data = Reference(ws, min_col=2, min_row=1, max_row=5, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=5)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, 'A10')
wb.save('demo.xlsx')
其中条形图的行和列相关数据是可以变更的;下面是该代码的运行结果:
|