如何使用Python中的openpyxl创建Excel中的图表?

如何使用Python中的openpyxl创建Excel中的图表?

在这篇文章中,我将向您展示如何使用Python – Openpyxl模块在Excel中创建图表。我们将从头开始创建一个包含网球选手大满贯头衔数据的Excel电子表格,使用openpyxl模块创建条形图。

介绍..

微软公司已开始为Microsoft Excel表格提供新的扩展名为.xlsx,从Office 2007开始支持存储更多的行和列。这个更改已将Excel表格移动到基于XML的文件格式,ZIP压缩。世界由Microsoft电子表格统治着,人们一直在为各种目的而使用电子表格,其中一个用例是数据可视化。

准备..

Python的xlrd模块是Openpyxl模块的替代品,在支持Excel格式方面做得很好,但是此模块只能执行Excel电子表格的只读操作。openpyxl模块可以同时执行Excel表格的读写操作。

如何做..

1). 让我们首先安装openpyxl模块使用

pip install openpyxl.
Python

2). 定义用于创建新电子表格的数据。

# 导入模块
import openpyxl

# 定义您的文件名和数据
file_name = "charts.xlsx"
file_data = (['player', 'titles'], ['Federer', 20], ['Nadal', 20], ['Djokovic', 17], ['Murray', 3])
Python

3). 创建新的Excel文件。这将创建一个名为Sheet的默认工作表

xlsxfile = openpyxl.Workbook()
print(f"*** excel_file内部的sheet有 = {xlsxfile.sheetnames}")
new_workbook = xlsxfile['Sheet']
Python
*** excel_file内部的sheet = ['Sheet']
Python

4). 将有关网球选手及其大满贯头衔的数据添加到此表中。

for row, (player,titles) in enumerate(file_data, 1):
new_workbook['A{}'.format(row)].value = player
new_workbook['B{}'.format(row)].value = titles
Python

5). 最后将数据保存到file_name文件

xlsxfile.save(file_name)
Python

6). 将文件加载到内存中并列出所有工作表。请注意,我们只创建了一个工作表作为第2步的一部分。

import openpyxl
excel_file_data = openpyxl.load_workbook(file_name)
excel_file_data.sheetnames
Python
['Sheet']
Python

7). 获取第一个工作表并获取单元格的值,例如A2和B2。

sheet_values = excel_file_data['Sheet']
print(f" *** 工作表中的一个值为 - {sheet_values['A2'].value} - {sheet_values['B2'].value}")
Python
*** 工作表中的一个值为 - Federer - 20
Python

8). 输出我们电子表格中的所有行和列,以确保我们已正确插入了用于图表的数据。

for row in sheet_values:
for cell in row:
print(cell.value)
Python
player
titles
Federer
20
Nadal
20
Djokovic
17
Murray
3
Python

9). 从Openpyxl.chart中导入BarChart、Reference模块并创建Barchart对象

from openpyxl.chart import BarChart, Reference
chart = BarChart()
Python
#10.
# 填写基本信息,如图表标题,..

chart.title = "选手和大满贯"
chart.y_axis.title = '头衔'
chart.x_axis.title = '网球选手'
Python
#11.
# 现在,我们将创建对数据的引用并将数据附加到图表中。

data = Reference(sheet_values, min_row=2, max_row=5, min_col=1, max_col=2)
chart.add_data(data, from_rows=True, titles_from_data=True)
Python
#12.
# 最后,将图表添加到工作表并保存文件。

new_workbook.add_chart(chart, "A6")
xlsxfile.save(file_name)
Python

第11步通过一个参考对象创建一个引用框,从第2行第1列到第5行第2列,这是我们的数据所在的区域,当然头部是排除在外的。

使用.add_data()方法将数据添加到图表中。 **from_rows - 将每一行作为不同的数据系列。 **titles_from_data - 使用第一列来命名系列。

示例

将上述所有内容放在一起。

"""
Program: Create charts in excel using Python with openpyxl params: NA
output: Creates a chart.xlsx file with tennis players grandslam titles and a barchart representation of the data
"""
# import the module
import openpyxl
# Define your file name and data
file_name = "charts.xlsx"
file_data = ([ 'player' , 'titles' ], [ 'Federer' , 20 ], [ 'Nadal' , 20 ], [ 'Djokovic' , 17 ], [ 'Murray' , 3 ])
# create an excel spreadsheet
xlsxfile = openpyxl . Workbook ()
print ( f " *** The sheets inside the excel_file are = { xlsxfile . sheetnames } " )
new_workbook = xlsxfile [ 'Sheet' ]
for row , ( player , titles ) in enumerate ( file_data , 1 ):
new_workbook [ 'A {} ' . format ( row )] . value = player
new_workbook [ 'B {} ' . format ( row )] . value = titles
# save the spreadsheet
xlsxfile .save ( file_name )
# read the data
 excel_file_data = openpyxl . load_workbook ( file_name )
excel_file_data . sheetnames

sheet_values = excel_file_data [ 'Sheet' ]
print ( f " *** One of the value from the sheet is - { sheet_values [ 'A2' ] . value } - { sheet_values [ 'B2' ] . value } " )
for row in sheet_values :
for cell in row :
print ( cell . value ) # barchart creation from openpyxl.chart
import BarChart , Reference chart = BarChart ()
# Fill the basic information like chart title,..
chart . title = "Players & Grand Slams"
 chart . y_axis . title = 'Titles'
chart . x_axis . title = 'Tennis Players'
# Now we will create a reference to the data and append the data to the chart.
data = Reference ( sheet_values , min_row = 2 , max_row = 5 , min_col = 1 , max_col = 2 )
chart .
 add_data ( data , from_rows = True , titles_from_data = True )
# Finally, Add the chart to the sheet and save the file.
new_workbook . add_chart ( chart , "A6" )
 xlsxfile . save ( file_name )
Python

输出

当上述程序执行时,charts.xlsx将与此代码的目录中创建,其内容如下。

如何使用Python中的openpyxl创建Excel中的图表?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册