使用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、运行后的效果

相关推荐
笨笨聊运维19 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite19 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
小毛驴85019 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
闲人编程20 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_4577600020 小时前
Python 数据结构
数据结构·windows·python
刻BITTER20 小时前
用EXCEL 将单色屏幕的Bitmap 字模数据还原回图形
单片机·嵌入式硬件·excel·arduino
匿者 衍20 小时前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel
天外天-亮20 小时前
Vue + excel下载 + 水印
前端·vue.js·excel
合作小小程序员小小店21 小时前
web网页,在线%抖音,舆情,线性回归%分析系统demo,基于python+web+echart+nlp+线性回归,训练,数据库mysql
python·自然语言处理·回归·nlp·线性回归