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

相关推荐
香吧香6 分钟前
Python 基础语法总结
python
IT小盘8 分钟前
10-使用Reranker提升RAG回答准确率
人工智能·python
卷无止境14 分钟前
Python 装饰器:给函数穿件"外套",到底难在哪?
后端·python
大地之灯21 分钟前
从零做一个自己的 CLI
python·agent
gugucoding22 分钟前
34.【Java】I/O流(下):NIO与文件操作
java·python·nio
cui_ruicheng25 分钟前
Python数据分析(十三):Seaborn 统计可视化
开发语言·python·信息可视化·数据分析
如此这般英俊29 分钟前
手搓Claude Code-第十章 system_prompt
数据结构·人工智能·python·语言模型·自然语言处理·prompt
高洁011 小时前
VLA:驱动具身智能迈向通用的关键引擎
人工智能·python·深度学习·transformer·知识图谱
糖炒栗子03261 小时前
RF-DETR + DeepSpeed 双节点集群训练环境搭建操作记录
python
今天AI了吗1 小时前
【AI智能体】Hermes Agent 从部署到项目实战操作详解
java·人工智能·python·milvus