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

相关推荐
我今晚不熬夜16 分钟前
Excel文件解析
excel
测试199817 分钟前
如何编写好的测试用例?
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
Dreamsi_zh33 分钟前
Python爬虫04_Requests豆瓣电影爬取
开发语言·爬虫·python
230L1_78M69Q5487H34 分钟前
【机器学习】机器学习新手入门概述
人工智能·python·机器学习·scikit-learn
开开心心就好1 小时前
PDF转图片工具,一键转换高清无损
服务器·前端·智能手机·r语言·pdf·excel·batch
窗户1 小时前
有限Abel群的结构(3)
python·抽象代数·编程范式
饭来_1 小时前
Python 中使用 OpenCV 库来捕获摄像头视频流并在窗口中显示
python·opencv
码界筑梦坊1 小时前
91-基于Spark的空气质量数据分析可视化系统
大数据·python·数据分析·spark·django·numpy·pandas
坐吃山猪2 小时前
GitPython03-项目setup编译
git·python·setup
JavaEdge在掘金2 小时前
cursor1.3 重大更新!复刻 claude code!
python