Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để tạo biểu đồ trong excel bằng Python với openpyxl?

Trong bài này, tôi sẽ hướng dẫn bạn cách tạo biểu đồ trong excel bằng Python - Openpyxl module. Chúng tôi sẽ tạo một bảng tính excel từ đầu với tiêu đề grandlam của người chơi quần vợt làm dữ liệu để tạo biểu đồ thanh bằng cách sử dụng mô-đun openpyxl.

Giới thiệu ..

Microsoft office đã bắt đầu cung cấp một phần mở rộng mới cho trang tính Microsoft Excel, đó là .xlsx, từ Office 2007 để hỗ trợ lưu trữ nhiều hàng và cột hơn. Thay đổi này đã chuyển trang tính Excel sang định dạng tệp dựa trên XML với nén ZIP. Thế giới được thống trị bởi bảng tính của Microsoft, mọi người đã sử dụng bảng tính cho nhiều mục đích khác nhau và một trong những trường hợp sử dụng là để trực quan hóa dữ liệu.

Chuẩn bị ..

Mô-đun xlrd của Python một giải pháp thay thế cho mô-đun Openpyxl đã hỗ trợ tốt các định dạng Excel, tuy nhiên, mô-đun này có thể thực hiện các thao tác chỉ đọc trên bảng tính excel. Mô-đun openpyxl có thể thực hiện cả thao tác đọc và ghi trên trang tính Excel.

Cách thực hiện ..

1). Trước tiên, hãy để chúng tôi cài đặt mô-đun openpyxl bằng

pip install openpyxl.

2) .Xác định dữ liệu để tạo một bảng tính excel mới.

# 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])

3) Tạo một tệp Excel mới. Điều này tạo ra một trang tính mặc định, được gọi là Trang tính

xlsxfile = openpyxl.Workbook()
print(f" *** The sheets inside the excel_file are = {xlsxfile.sheetnames}")
new_workbook = xlsxfile['Sheet']


*** The sheets inside the excel_file are = ['Sheet']

4). Thêm dữ liệu về các vận động viên quần vợt và danh hiệu vô địch của họ vào trang tính này.

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

5) Cuối cùng lưu dữ liệu vào tệp tên_tệp

xlsxfile.save(file_name)

6). Nạp tệp vào bộ nhớ và liệt kê tất cả các trang tính. Lưu ý rằng chúng tôi chỉ tạo một trang tính như một phần của bước 2.

import openpyxl
excel_file_data = openpyxl.load_workbook(file_name)
excel_file_data.sheetnames


['Sheet']

7). Lấy trang tính đầu tiên và lấy giá trị của các ô, ví dụ:A2 và B2.

sheet_values = excel_file_data['Sheet']
print(f" *** One of the value from the sheet is - {sheet_values['A2'].value} - {sheet_values['B2'].value}")


*** One of the value from the sheet is - Federer - 20

8). Nhập tất cả các hàng và cột trong bảng tính của chúng tôi, chỉ để đảm bảo rằng chúng tôi đã chèn dữ liệu của mình đúng cách cho các biểu đồ.

for row in sheet_values:
for cell in row:
print(cell.value)


player
titles
Federer
20
Nadal
20
Djokovic
17
Murray
3

9). Nhập mô-đun BarChart, Tham chiếu từ openpyxl.chart và tạo đối tượng Barchart.

from openpyxl.chart import BarChart, Reference
chart = BarChart()


#10.
# Fill the basic information like chart title,..

chart.title = "Players & Grand Slams"
chart.y_axis.title = 'Titles'
chart.x_axis.title = 'Tennis Players'


#11.
# 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)


#12.
# Finally, Add the chart to the sheet and save the file.

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

Bước 11 tạo một hộp tham chiếu thông qua một đối tượng Tham chiếu, từ hàng 2 cột 1 đến hàng 5 cột 2, là khu vực chứa dữ liệu của chúng tôi, tiêu đề nguồn gốc bị loại trừ.

Dữ liệu được thêm vào biểu đồ bằng phương thức .add_data (). from_rows - làm cho mỗi hàng là một chuỗi dữ liệu khác nhau. title_from_data - sử dụng cột đầu tiên để đặt tên cho chuỗi.

Ví dụ

Chúng tôi sẽ tổng hợp mọi thứ được giải thích ở trên lại với nhau.

Chương trình
"""
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 )
*** The sheets inside the excel_file are = ['Sheet']
*** One of the value from the sheet is - Federer - 20
player
titles
Federer
20
Nadal
20
Djokovic
17
Murray
3

Đầu ra

Khi chương trình trên được thực thi, chart.xlsx sẽ được tạo trong cùng thư mục với mã này với bên dưới.

Làm thế nào để tạo biểu đồ trong excel bằng Python với openpyxl?