使用Python在excel里创建柱状图

一、前言

通过使用Python的openpyxl库,在excel里创建柱状图。openpyxl库提供了创建Excel图表的功能,包括柱状图(Bar Chart)。

二、程序展示

1、导入相关模块,新建excel

新建excel后,在excel的第一列创建一些数据。

python 复制代码
import openpyxl
from openpyxl.chart import BarChart
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(1,13):
    sheet['A'+str(i+1)] = i

2、创建柱状图

创建柱状图,并设置数据范围。

参数说明:工作表,最小行,最小列,最大行,最大列

sheet为工作表

1,1,1,13分别代表:min_col=1, min_row=1, max_col=1, max_row=13

python 复制代码
chart1 = BarChart()
chart_data_ref = openpyxl.chart.Reference(sheet, 1,1,1,13)
chart_range_ref = openpyxl.chart.Reference(sheet,1,1,10)

3、设置图标标题

图标标题、x轴和y轴数据标题。

python 复制代码
chart1.title = '图标'
chart1.x_axis.title = '月份'
chart1.y_axis.title = '生产量'

4、添加数据系列到图标

python 复制代码
chart1.add_data(chart_data_ref, titles_from_data=True)
chart1.set_categories(chart_range_ref)

5、保存图标和工作簿

python 复制代码
sheet.add_chart(chart1, 'f4')
wb.save('F:\python_study\表格\chart1.xlsx')

6、运行后的效果

相关推荐
青铜发条9 分钟前
【python】python进阶——logging日志模块
python
无规则ai40 分钟前
动手学深度学习(pytorch版):第六章节—卷积神经网络(1)从全连接层到卷积
人工智能·pytorch·python·深度学习·cnn
秋难降1 小时前
优雅的代码是什么样的?🫣
java·python·代码规范
二闹2 小时前
聊天怕被老板发现?摩斯密码来帮你
后端·python
mit6.8242 小时前
[RestGPT] OpenAPI规范(OAS)
人工智能·python
360安全应急响应中心2 小时前
Python代码保护之重置操作码映射的攻与防探究(一)
python·逆向
码界奇点3 小时前
Python内置函数全解析:30个核心函数语法、案例与最佳实践指南
linux·服务器·python
程序视点3 小时前
「Excel文件批量加密与合并工具推荐」高效办公必备神器 - 程序视点
excel
dreams_dream3 小时前
django错误记录
后端·python·django
MC皮蛋侠客4 小时前
使用Python实现DLT645-2007智能电表协议
python·网络协议·tcp/ip·能源