Reading xlsx files in python

Как читать excel-файлы (xlsx) при помощи Python

.xlsx – это расширение документа Excel, который может хранить большой объем данных в табличной форме. Более того, в электронной таблице Excel можно легко выполнять многие виды арифметических и логических вычислений.

Иногда программистам требуется прочитать данные из документа Excel. В Python для этого есть множество различных библиотек, например, xlrd , openpyxl и pandas . Сегодня мы поговорим о том, как читать excel-файлы (xlsx) при помощи Python, и рассмотрим примеры использования различных библиотек для этих целей.

Для начала

Для проверки примеров этого руководства потребуется какой-нибудь файл Excel с расширением .xlsx , содержащий какие-либо исходные данные. Вы можете использовать любой существующий файл Excel или создать новый. Мы создадим новый файл с именем sales.xlsx со следующими данными:

sales.xlsx

Sales Date Sales Person Amount
12/05/18 Sila Ahmed 60000
06/12/19 Mir Hossain 50000
09/08/20 Sarmin Jahan 45000
07/04/21 Mahmudul Hasan 30000

Этот файл мы и будем читать с помощью различных библиотек Python в следующей части этого руководства.

Чтение Excel-файла с помощью xlrd

Библиотека xlrd не устанавливается вместе с Python по умолчанию, так что ее придется установить. Последняя версия этой библиотеки, к сожалению, не поддерживает Excel-файлы с расширением .xlsx . Поэтому устанавливаем версию 1.2.0. Выполните следующую команду в терминале:

Читайте также:  Css примеры выпадающего меню

После завершения процесса установки создайте Python-файл, в котором мы будем писать скрипт для чтения файла sales.xlsx с помощью модуля xlrd.

Воспользуемся функцией open_workbook() для открытия файла xlsx для чтения. Этот файл Excel содержит только одну таблицу. Поэтому функция workbook.sheet_by_index() используется в скрипте со значением аргумента 0.

Затем используем вложенный цикл for . С его помощью мы будем перемещаться по ячейкам, перебирая строки и столбцы. Также в скрипте используются две функции range() для определения количества строк и столбцов в таблице.

Для чтения значения отдельной ячейки таблицы на каждой итерации цикла воспользуемся функцией cell_value() . Каждое поле в выводе будет разделено одним пробелом табуляции.

import xlrd # Open the Workbook workbook = xlrd.open_workbook("sales.xlsx") # Open the worksheet worksheet = workbook.sheet_by_index(0) # Iterate the rows and columns for i in range(0, 5): for j in range(0, 3): # Print the cell values with tab space print(worksheet.cell_value(i, j), end='\t') print('')

Запустим наш код и получим следующий результат.

Чтение Excel-файла с помощью openpyxl

Openpyxl – это еще одна библиотека Python для чтения файла .xlsx , и она также не идет по умолчанию вместе со стандартным пакетом Python. Чтобы установить этот модуль, выполните в терминале следующую команду:

После завершения процесса установки можно начинать писать код для чтения файла sales.xlsx.

Как и модуль xlrd, модуль openpyxl имеет функцию load_workbook() для открытия excel-файла для чтения. В качестве значения аргумента этой функции используется файл sales.xlsx.

Объект wookbook.active служит для чтения значений свойств max_row и max_column . Эти свойства используются во вложенных циклах for для чтения содержимого файла sales.xlsx.

Функцию range() используем для чтения строк таблицы, а функцию iter_cols() — для чтения столбцов. Каждое поле в выводе будет разделено двумя пробелами табуляции.

import openpyxl # Define variable to load the wookbook wookbook = openpyxl.load_workbook("sales.xlsx") # Define variable to read the active sheet: worksheet = wookbook.active # Iterate the loop to read the cell values for i in range(0, worksheet.max_row): for col in worksheet.iter_cols(1, worksheet.max_column): print(col[i].value, end="\t\t") print('')

Запустив наш скрипт, получим следующий вывод.

Чтение Excel-файла с помощью pandas

Если вы не пользовались библиотекой pandas ранее, вам необходимо ее установить. Как и остальные рассматриваемые библиотеки, она не поставляется вместе с Python. Выполните следующую команду, чтобы установить pandas из терминала.

После завершения процесса установки создаем файл Python и начинаем писать следующий скрипт для чтения файла sales.xlsx.

В библиотеке pandas есть функция read_excel() , которую можно использовать для чтения .xlsx -файлов. Ею мы и воспользуемся в нашем скрипте для чтения файла sales.xlsx.

Функция DataFrame() используется для чтения содержимого нашего файла и преобразования имеющейся там информации во фрейм данных. После мы сохраняем наш фрейм в переменной с именем data . А дальше выводим то, что лежит в data , в консоль.

import pandas as pd # Load the xlsx file excel_data = pd.read_excel('sales.xlsx') # Read the values of the file in the dataframe data = pd.DataFrame(excel_data, columns=['Sales Date', 'Sales Person', 'Amount']) # Print the content print("The content of the file is:\n", data)

После запуска кода мы получим следующий вывод.

Результат работы этого скрипта отличается от двух предыдущих примеров. В первом столбце печатаются номера строк, начиная с нуля. Значения даты выравниваются по центру. Имена продавцов выровнены по правому краю, а сумма — по левому.

Заключение

Программистам довольно часто приходится работать с файлами .xlsx . Сегодня мы рассмотрели, как читать excel-файлы при помощи Python. Мы разобрали три различных способа с использованием трех библиотек. Все эти библиотеки имеют разные функции и свойства.

Надеемся, теперь у вас не возникнет сложностей с чтением этих файлов в ваших скриптах.

Источник

How to read excel (xlsx) file in python

The .xlsx is the extension of the excel document that can store a large amount of data in tabular form, and many types of arithmetic and logical calculation can be done easily in an excel spreadsheet. Sometimes it is required to read the data from the excel document using Python script for programming purposes. Many modules exist in Python to read the excel document. Some of the useful modules are xlrd, openpyxl, and pandas. The ways to use these modules to read the excel file in Python have been shown in this tutorial.

Pre-requisite:

A dummy excel file with the .xlsx extension will be required to check the examples of this tutorial. You can use any existing excel file or create a new one. Here, a new excel file named sales.xlsx file has been created with the following data. This file has used for reading by using different python modules in the next part of this tutorial.

Sales Date Sales Person Amount
12/05/18 Sila Ahmed 60000
06/12/19 Mir Hossain 50000
09/08/20 Sarmin Jahan 45000
07/04/21 Mahmudul Hasan 30000

Example-1: Read excel file using xlrd

The xlrd module is not installed with Python by default. So, you have to install the module before using it. The latest version of this module does not support the excel file with the .xlsx extension. So, you have to install the 1.2.0 version of this module to read the xlsx file. Run the following command from the terminal to install the required version of xlrd.

After completing the installation process, create a python file with the following script to read the sales.xlsx file using the xlrd module. open_workbook() function is used in the script open the xlsx file for reading. This excel file contains one sheet only. So, the workbook.sheet_by_index() function has been used in the script with the argument value 0. Next, the nested ‘for’ loop has used to read the cell values of the worksheet using the row and column values. Two range() functions have been used in the script to define the row and column size based on the sheet data. The cell_value() function has used to read the particular cell value of the sheet in each iteration of the loop. Each field in the output will be separated by one tab space.

# Import the xlrd module
import xlrd

# Open the Workbook
workbook = xlrd. open_workbook ( «sales.xlsx» )

# Open the worksheet
worksheet = workbook. sheet_by_index ( 0 )

# Iterate the rows and columns
for i in range ( 0 , 5 ) :
for j in range ( 0 , 3 ) :
# Print the cell values with tab space
print ( worksheet. cell_value ( i , j ) , end = ‘ \t ‘ )
print ( » )

Output:

The following output will appear after executing the above script.

Example-2: Read excel file using openpyxl

The openpyxl is another python module to read the xlsx file, and it is also not installed with Python by default. Run the following command from the terminal to install this module before using it.

After completing the installation process, create a python file with the following script to read the sales.xlsx file. Like the xlrd module, the openpyxl module has the load_workbook() function to open the xlsx file for reading. The sales.xlsx file is used as the argument value of this function. The object of the wookbook.active has been created in the script to read the values of the max_row and the max_column properties. These properties have been used in the nested for loops to read the content of the sales.xlsx file. The range() function has been used to read the rows of the sheet, and the iter_cols() function has been used to read the columns of the sheet. Each field in the output will be separated by two tab spaces.

# Import openyxl module
import openpyxl

# Define variable to load the wookbook
wookbook = openpyxl. load_workbook ( «sales.xlsx» )

# Define variable to read the active sheet:
worksheet = wookbook. active

# Iterate the loop to read the cell values
for i in range ( 0 , worksheet. max_row ) :
for col in worksheet. iter_cols ( 1 , worksheet. max_column ) :
print ( col [ i ] . value , end = » \t \t » )
print ( » )

Output:

The following output will appear after executing the above script.

Example-3: Read excel file using pandas

The pandas module is not installed with python-like the previous module. So, if you didn’t install it before, then you have to install it. Run the following command to install the pandas from the terminal.

After completing the installation process, create a python file with the following script to read the sales.xlsx file. The read_excel() function of pandas is used for reading the xlsx file. This function has used in the script to read the sales.xlsx file. The DataFrame() function has used here to read the content of the xlsx file in the data frame and store the values in the variable named data. The value of the data has been printed later.

# Import pandas
import pandas as pd

# Load the xlsx file
excel_data = pd. read_excel ( ‘sales.xlsx’ )
# Read the values of the file in the dataframe
data = pd. DataFrame ( excel_data , columns = [
‘Sales Date’ , ‘Sales Person’ , ‘Amount’ ] )
# Print the content
print ( «The content of the file is: \n » , data )

Output:

The following output will appear after executing the above script. The output of this script is different from the previous two examples. The row numbers are printed in the first column, where the row value has counted from 0. The date values are aligned centrally. The names of the salespersons are aligned right. The amount is aligned left.

Conclusion:

The python users need to work with xlsx files for different programming purposes. Three different ways to read the xlsx file have been shown in this tutorial by using three python modules. Each module has different functions and properties to read the xlsx file. This tutorial will help python users read the xlsx file easily using the python script after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью