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

相关推荐
IVEN_6 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang8 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮8 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling8 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮11 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽11 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers