Read excel python xlsx

.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. Выполните следующую команду в терминале:

pip install xlrd == 1.2.0

После завершения процесса установки создайте 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. Чтобы установить этот модуль, выполните в терминале следующую команду:

pip install openpyxl

После завершения процесса установки можно начинать писать код для чтения файла 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="tt")
    print('')

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

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

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

pip install 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. Мы разобрали три различных способа с использованием трех библиотек. Все эти библиотеки имеют разные функции и свойства.

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

Время на прочтение
10 мин

Количество просмотров 290K

Первая часть статьи была опубликована тут.

Как читать и редактировать Excel файлы при помощи openpyxl

ПЕРЕВОД
Оригинал статьи — www.datacamp.com/community/tutorials/python-excel-tutorial
Автор — Karlijn Willems

Эта библиотека пригодится, если вы хотите читать и редактировать файлы .xlsx, xlsm, xltx и xltm.

Установите openpyxl using pip. Общие рекомендации по установке этой библиотеки — сделать это в виртуальной среде Python без системных библиотек. Вы можете использовать виртуальную среду для создания изолированных сред Python: она создает папку, содержащую все необходимые файлы, для использования библиотек, которые потребуются для Python.

Перейдите в директорию, в которой находится ваш проект, и повторно активируйте виртуальную среду venv. Затем перейдите к установке openpyxl с помощью pip, чтобы убедиться, что вы можете читать и записывать с ним файлы:

# Activate virtualenv
$ source activate venv

# Install `openpyxl` in `venv`
$ pip install openpyxl

Теперь, когда вы установили openpyxl, вы можете начать загрузку данных. Но что именно это за данные? Например, в книге с данными, которые вы пытаетесь получить на Python, есть следующие листы:

Функция load_workbook () принимает имя файла в качестве аргумента и возвращает объект рабочей книги, который представляет файл. Это можно проверить запуском type (wb). Не забудьте убедиться, что вы находитесь в правильной директории, где расположена электронная таблица. В противном случае вы получите сообщение об ошибке при импорте.

# Import `load_workbook` module from `openpyxl`
from openpyxl import load_workbook

# Load in the workbook
wb = load_workbook('./test.xlsx')

# Get sheet names
print(wb.get_sheet_names())

Помните, вы можете изменить рабочий каталог с помощью os.chdir (). Фрагмент кода выше возвращает имена листов книги, загруженной в Python. Вы можете использовать эту информацию для получения отдельных листов книги. Также вы можете проверить, какой лист активен в настоящий момент с помощью wb.active. В приведенном ниже коде, вы также можете использовать его для загрузки данных на другом листе книги:

# Get a sheet by name 
sheet = wb.get_sheet_by_name('Sheet3')

# Print the sheet title 
sheet.title

# Get currently active sheet
anotherSheet = wb.active

# Check `anotherSheet` 
anotherSheet

На первый взгляд, с этими объектами Worksheet мало что можно сделать. Однако, можно извлекать значения из определенных ячеек на листе книги, используя квадратные скобки [], к которым нужно передавать точную ячейку, из которой вы хотите получить значение.

Обратите внимание, это похоже на выбор, получение и индексирование массивов NumPy и Pandas DataFrames, но это еще не все, что нужно сделать, чтобы получить значение. Нужно еще добавить значение атрибута:

# Retrieve the value of a certain cell
sheet['A1'].value

# Select element 'B2' of your sheet 
c = sheet['B2']

# Retrieve the row number of your element
c.row

# Retrieve the column letter of your element
c.column

# Retrieve the coordinates of the cell 
c.coordinate

Помимо value, есть и другие атрибуты, которые можно использовать для проверки ячейки, а именно row, column и coordinate:

Атрибут row вернет 2;
Добавление атрибута column к “С” даст вам «B»;
coordinate вернет «B2».

Вы также можете получить значения ячеек с помощью функции cell (). Передайте аргументы row и column, добавьте значения к этим аргументам, которые соответствуют значениям ячейки, которые вы хотите получить, и, конечно же, не забудьте добавить атрибут value:

# Retrieve cell value 
sheet.cell(row=1, column=2).value

# Print out values in column 2 
for i in range(1, 4):
     print(i, sheet.cell(row=i, column=2).value)

Обратите внимание: если вы не укажете значение атрибута value, вы получите <Cell Sheet3.B1>, который ничего не говорит о значении, которое содержится в этой конкретной ячейке.

Вы используете цикл с помощью функции range (), чтобы помочь вам вывести значения строк, которые имеют значения в столбце 2. Если эти конкретные ячейки пусты, вы получите None.
Более того, существуют специальные функции, которые вы можете вызвать, чтобы получить другие значения, например get_column_letter () и column_index_from_string.

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

# Import relevant modules from `openpyxl.utils`
from openpyxl.utils import get_column_letter, column_index_from_string

# Return 'A'
get_column_letter(1)

# Return '1'
column_index_from_string('A')

Вы уже получили значения для строк, которые имеют значения в определенном столбце, но что нужно сделать, если нужно вывести строки файла, не сосредотачиваясь только на одном столбце?

Конечно, использовать другой цикл.

Например, вы хотите сосредоточиться на области, находящейся между «A1» и «C3», где первый указывает левый верхний угол, а второй — правый нижний угол области, на которой вы хотите сфокусироваться. Эта область будет так называемой cellObj, которую вы видите в первой строке кода ниже. Затем вы указываете, что для каждой ячейки, которая находится в этой области, вы хотите вывести координату и значение, которое содержится в этой ячейке. После окончания каждой строки вы хотите выводить сообщение-сигнал о том, что строка этой области cellObj была выведена.

# Print row per row
for cellObj in sheet['A1':'C3']:
      for cell in cellObj:
              print(cells.coordinate, cells.value)
      print('--- END ---')

Обратите внимание, что выбор области очень похож на выбор, получение и индексирование списка и элементы NumPy, где вы также используете квадратные скобки и двоеточие чтобы указать область, из которой вы хотите получить значения. Кроме того, вышеприведенный цикл также хорошо использует атрибуты ячейки!

Чтобы визуализировать описанное выше, возможно, вы захотите проверить результат, который вернет вам завершенный цикл:

('A1', u'M')
('B1', u'N')
('C1', u'O')
--- END ---
('A2', 10L)
('B2', 11L)
('C2', 12L)
--- END ---
('A3', 14L)
('B3', 15L)
('C3', 16L)
--- END ---

Наконец, есть некоторые атрибуты, которые вы можете использовать для проверки результата импорта, а именно max_row и max_column. Эти атрибуты, конечно, являются общими способами обеспечения правильной загрузки данных, но тем не менее в данном случае они могут и будут полезны.

# Retrieve the maximum amount of rows 
sheet.max_row

# Retrieve the maximum amount of columns
sheet.max_column

Это все очень классно, но мы почти слышим, что вы сейчас думаете, что это ужасно трудный способ работать с файлами, особенно если нужно еще и управлять данными.
Должно быть что-то проще, не так ли? Всё так!

Openpyxl имеет поддержку Pandas DataFrames. И можно использовать функцию DataFrame () из пакета Pandas, чтобы поместить значения листа в DataFrame:

# Import `pandas` 
import pandas as pd

# Convert Sheet to DataFrame
df = pd.DataFrame(sheet.values)
Если вы хотите указать заголовки и индексы, вам нужно добавить немного больше кода:
# Put the sheet values in `data`
data = sheet.values

# Indicate the columns in the sheet values
cols = next(data)[1:]

# Convert your data to a list
data = list(data)

# Read in the data at index 0 for the indices
idx = [r[0] for r in data]

# Slice the data at index 1 
data = (islice(r, 1, None) for r in data)

# Make your DataFrame
df = pd.DataFrame(data, index=idx, columns=cols)

Затем вы можете начать управлять данными при помощи всех функций, которые есть в Pandas. Но помните, что вы находитесь в виртуальной среде, поэтому, если библиотека еще не подключена, вам нужно будет установить ее снова через pip.

Чтобы записать Pandas DataFrames обратно в файл Excel, можно использовать функцию dataframe_to_rows () из модуля utils:

# Import `dataframe_to_rows`
from openpyxl.utils.dataframe import dataframe_to_rows

# Initialize a workbook 
wb = Workbook()

# Get the worksheet in the active workbook
ws = wb.active

# Append the rows of the DataFrame to your worksheet
for r in dataframe_to_rows(df, index=True, header=True):
    ws.append(r)

Но это определенно не все! Библиотека openpyxl предлагает вам высокую гибкость в отношении того, как вы записываете свои данные в файлы Excel, изменяете стили ячеек или используете режим только для записи. Это делает ее одной из тех библиотек, которую вам точно необходимо знать, если вы часто работаете с электронными таблицами.

И не забудьте деактивировать виртуальную среду, когда закончите работу с данными!

Теперь давайте рассмотрим некоторые другие библиотеки, которые вы можете использовать для получения данных в электронной таблице на Python.

Готовы узнать больше?

Чтение и форматирование Excel файлов xlrd
Эта библиотека идеальна, если вы хотите читать данные и форматировать данные в файлах с расширением .xls или .xlsx.

# Import `xlrd`
import xlrd

# Open a workbook 
workbook = xlrd.open_workbook('example.xls')

# Loads only current sheets to memory
workbook = xlrd.open_workbook('example.xls', on_demand = True)

Если вы не хотите рассматривать всю книгу, можно использовать такие функции, как sheet_by_name () или sheet_by_index (), чтобы извлекать листы, которые необходимо использовать в анализе.

# Load a specific sheet by name
worksheet = workbook.sheet_by_name('Sheet1')

# Load a specific sheet by index 
worksheet = workbook.sheet_by_index(0)

# Retrieve the value from cell at indices (0,0) 
sheet.cell(0, 0).value

Наконец, можно получить значения по определенным координатам, обозначенным индексами.
О том, как xlwt и xlutils, соотносятся с xlrd расскажем дальше.

Запись данных в Excel файл при помощи xlrd

Если нужно создать электронные таблицы, в которых есть данные, кроме библиотеки XlsxWriter можно использовать библиотеки xlwt. Xlwt идеально подходит для записи и форматирования данных в файлы с расширением .xls.

Когда вы вручную хотите записать в файл, это будет выглядеть так:

# Import `xlwt` 
import xlwt

# Initialize a workbook 
book = xlwt.Workbook(encoding="utf-8")

# Add a sheet to the workbook 
sheet1 = book.add_sheet("Python Sheet 1") 

# Write to the sheet of the workbook 
sheet1.write(0, 0, "This is the First Cell of the First Sheet") 

# Save the workbook 
book.save("spreadsheet.xls")

Если нужно записать данные в файл, то для минимизации ручного труда можно прибегнуть к циклу for. Это позволит немного автоматизировать процесс. Делаем скрипт, в котором создается книга, в которую добавляется лист. Далее указываем список со столбцами и со значениями, которые будут перенесены на рабочий лист.

Цикл for будет следить за тем, чтобы все значения попадали в файл: задаем, что с каждым элементом в диапазоне от 0 до 4 (5 не включено) мы собираемся производить действия. Будем заполнять значения строка за строкой. Для этого указываем row элемент, который будет “прыгать” в каждом цикле. А далее у нас следующий for цикл, который пройдется по столбцам листа. Задаем условие, что для каждой строки на листе смотрим на столбец и заполняем значение для каждого столбца в строке. Когда заполнили все столбцы строки значениями, переходим к следующей строке, пока не заполним все имеющиеся строки.

# Initialize a workbook
book = xlwt.Workbook()

# Add a sheet to the workbook
sheet1 = book.add_sheet("Sheet1")

# The data
cols = ["A", "B", "C", "D", "E"]
txt = [0,1,2,3,4]

# Loop over the rows and columns and fill in the values
for num in range(5):
      row = sheet1.row(num)
      for index, col in enumerate(cols):
          value = txt[index] + num
          row.write(index, value)

# Save the result
book.save("test.xls")

В качестве примера скриншот результирующего файла:

Теперь, когда вы видели, как xlrd и xlwt взаимодействуют вместе, пришло время посмотреть на библиотеку, которая тесно связана с этими двумя: xlutils.

Коллекция утилит xlutils

Эта библиотека в основном представляет собой набор утилит, для которых требуются как xlrd, так и xlwt. Включает в себя возможность копировать и изменять/фильтровать существующие файлы. Вообще говоря, оба этих случая подпадают теперь под openpyxl.

Использование pyexcel для чтения файлов .xls или .xlsx

Еще одна библиотека, которую можно использовать для чтения данных таблиц в Python — pyexcel. Это Python Wrapper, который предоставляет один API для чтения, обработки и записи данных в файлах .csv, .ods, .xls, .xlsx и .xlsm.

Чтобы получить данные в массиве, можно использовать функцию get_array (), которая содержится в пакете pyexcel:

# Import `pyexcel`
import pyexcel

# Get an array from the data
my_array = pyexcel.get_array(file_name="test.xls")
 
Также можно получить данные в упорядоченном словаре списков, используя функцию get_dict ():
# Import `OrderedDict` module 
from pyexcel._compact import OrderedDict

# Get your data in an ordered dictionary of lists
my_dict = pyexcel.get_dict(file_name="test.xls", name_columns_by_row=0)

# Get your data in a dictionary of 2D arrays
book_dict = pyexcel.get_book_dict(file_name="test.xls")

Однако, если вы хотите вернуть в словарь двумерные массивы или, иными словами, получить все листы книги в одном словаре, стоит использовать функцию get_book_dict ().

Имейте в виду, что обе упомянутые структуры данных, массивы и словари вашей электронной таблицы, позволяют создавать DataFrames ваших данных с помощью pd.DataFrame (). Это упростит обработку ваших данных!

Наконец, вы можете просто получить записи с pyexcel благодаря функции get_records (). Просто передайте аргумент file_name функции и обратно получите список словарей:

# Retrieve the records of the file
records = pyexcel.get_records(file_name="test.xls")

Записи файлов при помощи pyexcel

Так же, как загрузить данные в массивы с помощью этого пакета, можно также легко экспортировать массивы обратно в электронную таблицу. Для этого используется функция save_as () с передачей массива и имени целевого файла в аргумент dest_file_name:

# Get the data
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Save the array to a file
pyexcel.save_as(array=data, dest_file_name="array_data.xls")

Обратите внимание: если указать разделитель, то можно добавить аргумент dest_delimiter и передать символ, который хотите использовать, в качестве разделителя между “”.

Однако, если у вас есть словарь, нужно будет использовать функцию save_book_as (). Передайте двумерный словарь в bookdict и укажите имя файла, и все ОК:

# The data
2d_array_dictionary = {'Sheet 1': [
                                   ['ID', 'AGE', 'SCORE']
                                   [1, 22, 5],
                                   [2, 15, 6],
                                   [3, 28, 9]
                                  ],
                       'Sheet 2': [
                                    ['X', 'Y', 'Z'],
                                    [1, 2, 3],
                                    [4, 5, 6]
                                    [7, 8, 9]
                                  ],
                       'Sheet 3': [
                                    ['M', 'N', 'O', 'P'],
                                    [10, 11, 12, 13],
                                    [14, 15, 16, 17]
                                    [18, 19, 20, 21]
                                   ]}

# Save the data to a file                        
pyexcel.save_book_as(bookdict=2d_array_dictionary, dest_file_name="2d_array_data.xls")

Помните, что когда используете код, который напечатан в фрагменте кода выше, порядок данных в словаре не будет сохранен!

Чтение и запись .csv файлов

Если вы все еще ищете библиотеки, которые позволяют загружать и записывать данные в CSV-файлы, кроме Pandas, рекомендуем библиотеку csv:

# import `csv`
import csv

# Read in csv file 
for row in csv.reader(open('data.csv'), delimiter=','):
      print(row)
      
# Write csv file
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
outfile = open('data.csv', 'w')
writer = csv.writer(outfile, delimiter=';', quotechar='"')
writer.writerows(data)
outfile.close()

Обратите внимание, что NumPy имеет функцию genfromtxt (), которая позволяет загружать данные, содержащиеся в CSV-файлах в массивах, которые затем можно помещать в DataFrames.

Финальная проверка данных

Когда данные подготовлены, не забудьте последний шаг: проверьте правильность загрузки данных. Если вы поместили свои данные в DataFrame, вы можете легко и быстро проверить, был ли импорт успешным, выполнив следующие команды:

# Check the first entries of the DataFrame
df1.head()

# Check the last entries of the DataFrame
df1.tail()

Note: Используйте DataCamp Pandas Cheat Sheet, когда вы планируете загружать файлы в виде Pandas DataFrames.

Если данные в массиве, вы можете проверить его, используя следующие атрибуты массива: shape, ndim, dtype и т.д.:

# Inspect the shape 
data.shape

# Inspect the number of dimensions
data.ndim

# Inspect the data type
data.dtype

Что дальше?

Поздравляем, теперь вы знаете, как читать файлы Excel в Python :) Но импорт данных — это только начало рабочего процесса в области данных. Когда у вас есть данные из электронных таблиц в вашей среде, вы можете сосредоточиться на том, что действительно важно: на анализе данных.

Если вы хотите глубже погрузиться в тему — знакомьтесь с PyXll, которая позволяет записывать функции в Python и вызывать их в Excel.

Pandas можно использовать для чтения и записи файлов Excel с помощью Python. Это работает по аналогии с другими форматами. В этом материале рассмотрим, как это делается с помощью DataFrame.

Помимо чтения и записи рассмотрим, как записывать несколько DataFrame в Excel-файл, как считывать определенные строки и колонки из таблицы и как задавать имена для одной или нескольких таблиц в файле.

Установка Pandas

Для начала Pandas нужно установить. Проще всего это сделать с помощью pip.

Если у вас Windows, Linux или macOS:

pip install pandas # или pip3

В процессе можно столкнуться с ошибками ModuleNotFoundError или ImportError при попытке запустить этот код. Например:

ModuleNotFoundError: No module named 'openpyxl'

В таком случае нужно установить недостающие модули:

pip install openpyxl xlsxwriter xlrd  # или pip3

Будем хранить информацию, которую нужно записать в файл Excel, в DataFrame. А с помощью встроенной функции to_excel() ее можно будет записать в Excel.

Сначала импортируем модуль pandas. Потом используем словарь для заполнения DataFrame:


import pandas as pd

df = pd.DataFrame({'Name': ['Manchester City', 'Real Madrid', 'Liverpool',
'FC Bayern München', 'FC Barcelona', 'Juventus'],
'League': ['English Premier League (1)', 'Spain Primera Division (1)',
'English Premier League (1)', 'German 1. Bundesliga (1)',
'Spain Primera Division (1)', 'Italian Serie A (1)'],
'TransferBudget': [176000000, 188500000, 90000000,
100000000, 180500000, 105000000]})

Ключи в словаре — это названия колонок. А значения станут строками с информацией.

Теперь можно использовать функцию to_excel() для записи содержимого в файл. Единственный аргумент — это путь к файлу:


df.to_excel('./teams.xlsx')

А вот и созданный файл Excel:

файл Excel в python

Стоит обратить внимание на то, что в этом примере не использовались параметры. Таким образом название листа в файле останется по умолчанию — «Sheet1». В файле может быть и дополнительная колонка с числами. Эти числа представляют собой индексы, которые взяты напрямую из DataFrame.

Поменять название листа можно, добавив параметр sheet_name в вызов to_excel():


df.to_excel('./teams.xlsx', sheet_name='Budgets', index=False)

Также можно добавили параметр index со значением False, чтобы избавиться от колонки с индексами. Теперь файл Excel будет выглядеть следующим образом:

Чтение и запись файлов Excel (XLSX) в Python

Запись нескольких DataFrame в файл Excel

Также есть возможность записать несколько DataFrame в файл Excel. Для этого можно указать отдельный лист для каждого объекта:


salaries1 = pd.DataFrame({'Name': ['L. Messi', 'Cristiano Ronaldo', 'J. Oblak'],
'Salary': [560000, 220000, 125000]})

salaries2 = pd.DataFrame({'Name': ['K. De Bruyne', 'Neymar Jr', 'R. Lewandowski'],
'Salary': [370000, 270000, 240000]})

salaries3 = pd.DataFrame({'Name': ['Alisson', 'M. ter Stegen', 'M. Salah'],
'Salary': [160000, 260000, 250000]})

salary_sheets = {'Group1': salaries1, 'Group2': salaries2, 'Group3': salaries3}
writer = pd.ExcelWriter('./salaries.xlsx', engine='xlsxwriter')

for sheet_name in salary_sheets.keys():
salary_sheets[sheet_name].to_excel(writer, sheet_name=sheet_name, index=False)

writer.save()

Здесь создаются 3 разных DataFrame с разными названиями, которые включают имена сотрудников, а также размер их зарплаты. Каждый объект заполняется соответствующим словарем.

Объединим все три в переменной salary_sheets, где каждый ключ будет названием листа, а значение — объектом DataFrame.

Дальше используем движок xlsxwriter для создания объекта writer. Он и передается функции to_excel().

Перед записью пройдемся по ключам salary_sheets и для каждого ключа запишем содержимое в лист с соответствующим именем. Вот сгенерированный файл:

Чтение и запись файлов Excel (XLSX) в Python

Можно увидеть, что в этом файле Excel есть три листа: Group1, Group2 и Group3. Каждый из этих листов содержит имена сотрудников и их зарплаты в соответствии с данными в трех DataFrame из кода.

Параметр движка в функции to_excel() используется для определения модуля, который задействуется библиотекой Pandas для создания файла Excel. В этом случае использовался xslswriter, который нужен для работы с классом ExcelWriter. Разные движка можно определять в соответствии с их функциями.

В зависимости от установленных в системе модулей Python другими параметрами для движка могут быть openpyxl (для xlsx или xlsm) и xlwt (для xls). Подробности о модуле xlswriter можно найти в официальной документации.

Наконец, в коде была строка writer.save(), которая нужна для сохранения файла на диске.

Чтение файлов Excel с python

По аналогии с записью объектов DataFrame в файл Excel, эти файлы можно и читать, сохраняя данные в объект DataFrame. Для этого достаточно воспользоваться функцией read_excel():


top_players = pd.read_excel('./top_players.xlsx')
top_players.head()

Содержимое финального объекта можно посмотреть с помощью функции head().

Примечание:

Этот способ самый простой, но он и способен прочесть лишь содержимое первого листа.

Посмотрим на вывод функции head():

Name Age Overall Potential Positions Club
0 L. Messi 33 93 93 RW,ST,CF FC Barcelona
1 Cristiano Ronaldo 35 92 92 ST,LW Juventus
2 J. Oblak 27 91 93 GK Atlético Madrid
3 K. De Bruyne 29 91 91 CAM,CM Manchester City
4 Neymar Jr 28 91 91 LW,CAM Paris Saint-Germain

Pandas присваивает метку строки или числовой индекс объекту DataFrame по умолчанию при использовании функции read_excel().

Это поведение можно переписать, передав одну из колонок из файла в качестве параметра index_col:


top_players = pd.read_excel('./top_players.xlsx', index_col='Name')
top_players.head()

Результат будет следующим:

Name Age Overall Potential Positions Club
L. Messi 33 93 93 RW,ST,CF FC Barcelona
Cristiano Ronaldo 35 92 92 ST,LW Juventus
J. Oblak 27 91 93 GK Atlético Madrid
K. De Bruyne 29 91 91 CAM,CM Manchester City
Neymar Jr 28 91 91 LW,CAM Paris Saint-Germain

В этом примере индекс по умолчанию был заменен на колонку «Name» из файла. Однако этот способ стоит использовать только при наличии колонки со значениями, которые могут стать заменой для индексов.

Чтение определенных колонок из файла Excel

Иногда удобно прочитать содержимое файла целиком, но бывают случаи, когда требуется получить доступ к определенному элементу. Например, нужно считать значение элемента и присвоить его полю объекта.

Это делается с помощью функции read_excel() и параметра usecols. Например, можно ограничить функцию, чтобы она читала только определенные колонки. Добавим параметр, чтобы он читал колонки, которые соответствуют значениям «Name», «Overall» и «Potential».

Для этого укажем числовой индекс каждой колонки:


cols = [0, 2, 3]

top_players = pd.read_excel('./top_players.xlsx', usecols=cols)
top_players.head()

Вот что выдаст этот код:

Name Overall Potential
0 L. Messi 93 93
1 Cristiano Ronaldo 92 92
2 J. Oblak 91 93
3 K. De Bruyne 91 91
4 Neymar Jr 91 91

Таким образом возвращаются лишь колонки из списка cols.

В DataFrame много встроенных возможностей. Легко изменять, добавлять и агрегировать данные. Даже можно строить сводные таблицы. И все это сохраняется в Excel одной строкой кода.

Рекомендую изучить DataFrame в моих уроках по Pandas.

Выводы

В этом материале были рассмотрены функции read_excel() и to_excel() из библиотеки Pandas. С их помощью можно считывать данные из файлов Excel и выполнять запись в них. С помощью различных параметров есть возможность менять поведение функций, создавая нужные файлы, не просто копируя содержимое из объекта DataFrame.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    One can retrieve information from a spreadsheet. Reading, writing, or modifying the data can be done in Python can be done in using different methods. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work. Here, we will see the different methods to read our excel file.

    Required Module

    pip install xlrd

    Input File: 

    Method 1: Reading an excel file using Python using Pandas

    In this method, We will first import the Pandas module then we will use Pandas to read our excel file. You can read more operations using the excel file using Pandas in this article. Click here

    Python3

    import pandas as pd

    dataframe1 = pd.read_excel('book2.xlsx')

    print(dataframe1)

    Output:

    Method 2: Reading an excel file using Python using openpyxl

    The load_workbook() function opens the Books.xlsx file for reading. This file is passed as an argument to this function. The object of the dataframe.active has been created in the script to read the values of the max_row and the max_column properties. These values are used in the loops to read the content of the Books2.xlsx file. You can read other operations using openpyxl in this article.

    Python3

    import openpyxl

    dataframe = openpyxl.load_workbook("Book2.xlsx")

    dataframe1 = dataframe.active

    for row in range(0, dataframe1.max_row):

        for col in dataframe1.iter_cols(1, dataframe1.max_column):

            print(col[row].value)

    Output: 

    Method 3: Reading an excel file using Python using Xlwings

    Xlwings can be used to insert data in an Excel file similarly as it reads from an Excel file. Data can be provided as a list or a single input to a certain cell or a selection of cells. You can read other operations using Xlwings in this article.

    Python3

    import xlwings as xw

    ws = xw.Book("Book2.xlsx").sheets['Sheet1']

    v1 = ws.range("A1:A7").value

    print("Result:", v1, v2)

    Output:

    Result: ['Name  Age    Stream  Percentage', 
    '0      Ankit   18      Math          95', 
    '1      Rahul   19   Science          90', 
    '2    Shaurya   20  Commerce          85', 
    '3  Aishwarya   18      Math          80', 
    '4   Priyanka   19   Science          75', 
    None]

    RECOMMENDED ARTICLE – How to Automate an Excel Sheet in Python?

    Like Article

    Save Article

    In this brief Python tutorial, we will learn how to read Excel (xlsx) files using Python. Specifically, we will read xlsx files in Python using the Python module openpyxl. First, we start by the simplest example of reading a xlsx file in Python. Second, we will learn how to read multiple Excel files using Python.

    In previous posts, we have learned how to use Pandas read_excel method to import xlsx files with Python. As previously mentioned, however, we will use another package called openpyxl in this post. In the next paragraph, we will learn how to install openpyxl.

    Openpyxl Syntax

    Basically, here’s the simplest form of using openpyxl for reading a xlsx file in Python:

    import openpyxl
    from pathlib import Path
    
    xlsx_file = Path('SimData', 'play_data.xlsx')
    wb_obj = openpyxl.load_workbook(xlsx_file) 
    
    # Read the active sheet:
    sheet = wb_obj.activeCode language: Python (python)

    how to read xlsx files in python

    It is, of course, also possible to learn how to read, write, and append to files in Python (e.g., text files). Make sure to check that post out, as well.

    Prerequisites: Python and Openpyxl

    Now, before we will learn what Openpyxl is, we need to make sure that we have both Python 3 and the module openpyxl installed. One easy way to install Python is to download a Python distribution such as Anaconda or ActivePython. Openpyxl, on the other hand, can, as with many Python packages, be installed using both pip and conda. Now, using pip we type the following in a command prompt or terminal window, pip install openpyxl and using conda we type this; conda install openpyxl. Note, sometimes when we are installing Python packages with pip, we may notice that we don’t have the latest version of pip. Luckily, it is quite easy to upgrade pip to the latest version using pip.

    learn all about reading excel files in python

    Example file 1 (xlsx)

    What is the use of Openpyxl in Python?

    Openpyxl is a Python module that can read and write Excel (with extension xlsx/xlsm/xltx/xltm) files. Furthermore, this module enables a Python script to modify Excel files. For instance, if we want to go through thousands of rows but just read specific data points and make small changes to these points, we can do this based on some criteria with openpyxl.

    How do I read an Excel (xlsx) File in Python?

    Now, the general method for reading xlsx files in Python (with openpyxl) is to import openpyxl (import openpyxl) and then read the workbook: wb = openpyxl.load_workbook(PATH_TO_EXCEL_FILE). In this post, we will learn more about this, of course.

    How to Read an Excel (xlsx) File in Python

    Now, in this section, we will be reading an xlsx file in Python using openpyxl. In a previous section, we have already been familiarized with the general template (syntax) for reading an Excel file using openpyxl and we will now get into this module in more detail. Note we will also work with the Path method from the Pathlib module.

    1. Import the Needed Modules

    In the first step, to reading an xlsx file in Python, we need to import the modules we need. That is, we will import Path and openpyxl:

    import openpyxl
    from pathlib import PathCode language: Python (python)

    reading excel (xlsx) files in python

    2. Setting the Path to the Excel (xlsx) File

    In the second step, we will create a variable using Path. Furthermore, this variable will point at the location and filename of the Excel file we want to import with Python:

    # Setting the path to the xlsx file:
    xlsx_file = Path('SimData', 'play_data.xlsx')</code></pre>Code language: Python (python)

    reading xlsx files in python

    Note, “SimData” is a subdirectory to that of the Python script (or notebook). That is, if we were to store the Excel file in a completely different directory, we need to put in the full path. For example, xlsx_file = Path(Path.home(), 'Documents', 'SimData', 'play_data.xlsx')if the data is stored in the Documents in our home directory.

    3. Read the Excel File (Workbook)

    In the third step, we are going to use Python to read the xlsx file. Now, we are using the load_workbook() method:

    wb_obj = openpyxl.load_workbook(xlsx_file)Code language: Python (python)

    how to read excel in python

    4. Read the Active Sheet from the Excel file

    Now, in the fourth step, we are going to read the active sheet using the active method:

    sheet = wb_obj.activeCode language: Python (python)

    python read xlsx files and print the sheet

    Note, if we know the sheet name we can also use this to read the sheet we want: play_data = wb_obj['play_data']

    5. Work or Manipulate the Excel Sheet

    In the final and fifth steps, we can work or manipulate the Excel sheet we have imported with Python. For example, if we want to get the value from a specific cell, we can do as follows:

    print(sheet["C2"].value)Code language: Python (python)

    Another example of what we can do with the spreadsheet in Python is we can iterate through the rows and print them:

    for row in sheet.iter_rows(max_row=6):
        for cell in row:
            print(cell.value, end=" ")
        print()Code language: Python (python)

    Note that we used the max_row and set it to 6 to print the six first rows from the Excel file.

    6. Bonus: Determining the Number of Rows and Columns in the Excel File

    In the sixth, and bonus step, we are going to find out how many rows and columns we have in the example Excel file we have imported with Python:

    print(sheet.max_row, sheet.max_column)Code language: Python (python)

    learning how to read xlsx files in python

    Reading an Excel (xlsx) File to a Python Dictionary

    Now, before we learn how to read multiple xlsx files, we will import data from Excel into a Python dictionary. It’s quite simple, but for the example below, we need to know the column names before we start. If we want to find out the column names, we can run the following code (or open the Excel file):

    import openpyxl
    from pathlib import Path
    
    xlsx_file = Path('SimData', 'play_data.xlsx')
    wb_obj = openpyxl.load_workbook(xlsx_file)
    sheet = wb_obj.active
    
    col_names = []
    for column in sheet.iter_cols(1, sheet.max_column):
        col_names.append(column[0].value)
       
        
    print(col_names)Code language: Python (python)

    Creating a Dictionary from an Excel File

    In this section, we will finally read the Excel file using Python and create a dictionary.

    data = {}
    
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i == 0:
            data[row[1]] = []
            data[row[2]] = []
            data[row[3]] = []
            data[row[4]] = []
            data[row[5]] = []
            data[row[6]] = []
    
        else:
            data['Subject ID'].append(row[1])
            data['First Name'].append(row[2])
            data['Day'].append(row[3])
            data['Age'].append(row[4])
            data['RT'].append(row[5])
            data['Gender'].append(row[6])Code language: Python (python)

    Now, let’s walk through the code example above. First, we create a Python dictionary (data). Second, we loop through each row (using iter_rows), and we only go through the rows where there are values. Second, we have an if statement where we check if it’s the first row and add the keys to the dictionary. That is, we set the column names as keys. Third, we append the data to each key (column name) in the other statement.

    How to Read Multiple Excel (xlsx) Files in Python

    In this section, we will learn how to read multiple xlsx files in Python using openpyxl. Additionally to openpyxl and Path, we are also going to work with the os module.

    1. Import the Modules

    In the first step, we are going to import the modules Path, glob, and openpyxl:

    import glob
    import openpyxl
    from pathlib import PathCode language: Python (python)

    2. Read all xlsx Files in the Directory to a List

    Second, we will read all the .xlsx files in a subdirectory into a list. Now, we use the glob module together with Path:

    xlsx_files = [path for path in Path('XLSX_FILES').rglob('*.xlsx')]Code language: Python (python)

    3. Create Workbook Objects (i.e., read the xlsx files)

    Third, we can now read all the xlsx files using Python. Again, we will use the load_workbook method. However, this time we will loop through each file we found in the subdirectory,

    wbs = [openpyxl.load_workbook(wb) for wb in xlsx_files]Code language: Python (python)

    Now, in the code examples above, we are using Python list comprehension (twice, in both step 2 and 3). First, we create a list of all the xlsx files in the “XLSX_FILES” directory. Second, we loop through this list and create a list of workbooks. Of course, we could add this to the first line of code above.

    4. Work with the Imported Excel Files

    In the fourth step, we can now work with the imported excel files. For example, we can get the first file by adding “[0]” to the list. If we want to know the sheet names of this file we do like this:wbs[0].sheetnames . Many of the things we can do, and have done in the previous example on reading xlsx files in Python, can be done when we’ve read multiple Excel files.

    Notice this is one great example of how to use this programming language. Other examples are, for instance, to use it for renaming files in Python.

    Conclusion: Reading Excel (xlsx) Files in Python

    In conclusion, Openpyxl is a powerful Python library that enables developers to read, write, and manipulate Excel files using Python. This tutorial covered how to read an Excel (xlsx) file in Python using Openpyxl. We started by importing the necessary modules, setting the path to the Excel file, and then reading the file and its active sheet. We then explored how to work with the sheet and even determine the number of rows and columns in the file.

    Moreover, we also learned how to read an Excel file to a Python dictionary and create a dictionary from an Excel file. Finally, we learned how to read multiple Excel files in a directory by importing the required modules, reading all the xlsx files in the directory to a list, creating workbook objects, and working with the imported Excel files.

    By mastering these techniques, you can easily read and manipulate Excel files using Python, which can be incredibly useful in various data processing applications. So go ahead, try it out, and unlock the full potential of Openpyxl in your Python projects!

    It is, of course, possible to import data from various other file formats. For instance, read the post about parsing json files in Python to learn more about reading JSON files.

    Microsoft Excel is one of the most powerful spreadsheet software applications in the world, and it has become critical in all business processes. Companies across the world, both big and small, are using Microsoft Excel to store, organize, analyze, and visualize data.

    As a data professional, when you combine Python with Excel, you create a unique data analysis bundle that unlocks the value of the enterprise data.

    In this tutorial, we’re going to learn how to read and work with Excel files in Python.

    After you finish this tutorial, you’ll understand the following:

    • Loading Excel spreadsheets into pandas DataFrames
    • Working with an Excel workbook with multiple spreadsheets
    • Combining multiple spreadsheets
    • Reading Excel files using the xlrd package

    In this tutorial, we assume you know the fundamentals of pandas DataFrames. If you aren’t familiar with the pandas library, you might like to try our Pandas and NumPy Fundamentals – Dataquest.

    Let’s dive in.

    Reading Spreadsheets with Pandas

    Technically, multiple packages allow us to work with Excel files in Python. However, in this tutorial, we’ll use pandas and xlrd libraries to interact with Excel workbooks. Essentially, you can think of a pandas DataFrame as a spreadsheet with rows and columns stored in Series objects. Traversability of Series as iterable objects allows us to grab specific data easily. Once we load an Excel workbook into a pandas DataFrame, we can perform any kind of data analysis on the data.

    Before we proceed to the next step, let’s first download the following spreadsheet:

    Sales Data Excel Workbook — xlsx ver.

    The Excel workbook consists of two sheets that contain stationery sales data for 2020 and 2021.


    NOTE

    Although Excel spreadsheets can contain formula and also support formatting, pandas only imports Excel spreadsheets as flat files, and it doesn’t support spreadsheet formatting.


    To import the Excel spreadsheet into a pandas DataFrame, first, we need to import the pandas package and then use the read_excel() method:

    import pandas as pd
    df = pd.read_excel('sales_data.xlsx')
    
    display(df)
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2020-01-06 East Jones Pencil 95 1.99 189.05 True
    1 2020-02-09 Central Jardine Pencil 36 4.99 179.64 True
    2 2020-03-15 West Sorvino Pencil 56 2.99 167.44 True
    3 2020-04-01 East Jones Binder 60 4.99 299.40 False
    4 2020-05-05 Central Jardine Pencil 90 4.99 449.10 True
    5 2020-06-08 East Jones Binder 60 8.99 539.40 True
    6 2020-07-12 East Howard Binder 29 1.99 57.71 False
    7 2020-08-15 East Jones Pencil 35 4.99 174.65 True
    8 2020-09-01 Central Smith Desk 32 125.00 250.00 True
    9 2020-10-05 Central Morgan Binder 28 8.99 251.72 True
    10 2020-11-08 East Mike Pen 15 19.99 299.85 False
    11 2020-12-12 Central Smith Pencil 67 1.29 86.43 False

    If you want to load only a limited number of rows into the DataFrame, you can specify the number of rows using the nrows argument:

    df = pd.read_excel('sales_data.xlsx', nrows=5)
    display(df)
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2020-01-06 East Jones Pencil 95 1.99 189.05 True
    1 2020-02-09 Central Jardine Pencil 36 4.99 179.64 True
    2 2020-03-15 West Sorvino Pencil 56 2.99 167.44 True
    3 2020-04-01 East Jones Binder 60 4.99 299.40 False
    4 2020-05-05 Central Jardine Pencil 90 4.99 449.10 True

    Skipping a specific number of rows from the begining of a spreadsheet or skipping over a list of particular rows is available through the skiprows argument, as follows:

    df = pd.read_excel('sales_data.xlsx', skiprows=range(5))
    display(df)
    2020-05-05 00:00:00 Central Jardine Pencil 90 4.99 449.1 True
    0 2020-06-08 East Jones Binder 60 8.99 539.40 True
    1 2020-07-12 East Howard Binder 29 1.99 57.71 False
    2 2020-08-15 East Jones Pencil 35 4.99 174.65 True
    3 2020-09-01 Central Smith Desk 32 125.00 250.00 True
    4 2020-10-05 Central Morgan Binder 28 8.99 251.72 True
    5 2020-11-08 East Mike Pen 15 19.99 299.85 False
    6 2020-12-12 Central Smith Pencil 67 1.29 86.43 False

    The code above skips the first five rows and returns the rest of the data. Instead, the following code returns all the rows except for those with the mentioned indices:

    df = pd.read_excel('sales_data.xlsx', skiprows=[1, 4,7,10])
    display(df)
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2020-02-09 Central Jardine Pencil 36 4.99 179.64 True
    1 2020-03-15 West Sorvino Pencil 56 2.99 167.44 True
    2 2020-05-05 Central Jardine Pencil 90 4.99 449.10 True
    3 2020-06-08 East Jones Binder 60 8.99 539.40 True
    4 2020-08-15 East Jones Pencil 35 4.99 174.65 True
    5 2020-09-01 Central Smith Desk 32 125.00 250.00 True
    6 2020-11-08 East Mike Pen 15 19.99 299.85 False
    7 2020-12-12 Central Smith Pencil 67 1.29 86.43 False

    Another useful argument is usecols, which allows us to select spreadsheet columns with their letters, names, or positional numbers. Let’s see how it works:

    df = pd.read_excel('sales_data.xlsx', usecols='A:C,G')
    display(df)
    OrderDate Region Rep Total
    0 2020-01-06 East Jones 189.05
    1 2020-02-09 Central Jardine 179.64
    2 2020-03-15 West Sorvino 167.44
    3 2020-04-01 East Jones 299.40
    4 2020-05-05 Central Jardine 449.10
    5 2020-06-08 East Jones 539.40
    6 2020-07-12 East Howard 57.71
    7 2020-08-15 East Jones 174.65
    8 2020-09-01 Central Smith 250.00
    9 2020-10-05 Central Morgan 251.72
    10 2020-11-08 East Mike 299.85
    11 2020-12-12 Central Smith 86.43

    In the code above, the string assigned to the usecols argument contains a range of columns with : plus column G separated by a comma. Also, we’re able to provide a list of column names and assign it to the usecols argument, as follows:

    df = pd.read_excel('sales_data.xlsx', usecols=['OrderDate', 'Region', 'Rep', 'Total'])
    display(df)
    OrderDate Region Rep Total
    0 2020-01-06 East Jones 189.05
    1 2020-02-09 Central Jardine 179.64
    2 2020-03-15 West Sorvino 167.44
    3 2020-04-01 East Jones 299.40
    4 2020-05-05 Central Jardine 449.10
    5 2020-06-08 East Jones 539.40
    6 2020-07-12 East Howard 57.71
    7 2020-08-15 East Jones 174.65
    8 2020-09-01 Central Smith 250.00
    9 2020-10-05 Central Morgan 251.72
    10 2020-11-08 East Mike 299.85
    11 2020-12-12 Central Smith 86.43

    The usecols argument accepts a list of column numbers, too. The following code shows how we can pick up specific columns using their indices:

    df = pd.read_excel('sales_data.xlsx', usecols=[0, 1, 2, 6])
    display(df)
    OrderDate Region Rep Total
    0 2020-01-06 East Jones 189.05
    1 2020-02-09 Central Jardine 179.64
    2 2020-03-15 West Sorvino 167.44
    3 2020-04-01 East Jones 299.40
    4 2020-05-05 Central Jardine 449.10
    5 2020-06-08 East Jones 539.40
    6 2020-07-12 East Howard 57.71
    7 2020-08-15 East Jones 174.65
    8 2020-09-01 Central Smith 250.00
    9 2020-10-05 Central Morgan 251.72
    10 2020-11-08 East Mike 299.85
    11 2020-12-12 Central Smith 86.43

    Working with Multiple Spreadsheets

    Excel files or workbooks usually contain more than one spreadsheet. The pandas library allows us to load data from a specific sheet or combine multiple spreadsheets into a single DataFrame. In this section, we’ll explore how to use these valuable capabilities.

    By default, the read_excel() method reads the first Excel sheet with the index 0. However, we can choose the other sheets by assigning a particular sheet name, sheet index, or even a list of sheet names or indices to the sheet_name argument. Let’s try it:

    df = pd.read_excel('sales_data.xlsx', sheet_name='2021')
    display(df)
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2021-01-15 Central Gill Binder 46 8.99 413.54 True
    1 2021-02-01 Central Smith Binder 87 15.00 1305.00 True
    2 2021-03-07 West Sorvino Binder 27 19.99 139.93 True
    3 2021-04-10 Central Andrews Pencil 66 1.99 131.34 False
    4 2021-05-14 Central Gill Pencil 53 1.29 68.37 False
    5 2021-06-17 Central Tom Desk 15 125.00 625.00 True
    6 2021-07-04 East Jones Pen Set 62 4.99 309.38 True
    7 2021-08-07 Central Tom Pen Set 42 23.95 1005.90 True
    8 2021-09-10 Central Gill Pencil 47 1.29 9.03 True
    9 2021-10-14 West Thompson Binder 57 19.99 1139.43 False
    10 2021-11-17 Central Jardine Binder 11 4.99 54.89 False
    11 2021-12-04 Central Jardine Binder 94 19.99 1879.06 False

    The code above reads the second spreadsheet in the workbook, whose name is 2021. As mentioned before, we also can assign a sheet position number (zero-indexed) to the sheet_name argument. Let’s see how it works:

    df = pd.read_excel('sales_data.xlsx', sheet_name=1)
    display(df)
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2021-01-15 Central Gill Binder 46 8.99 413.54 True
    1 2021-02-01 Central Smith Binder 87 15.00 1305.00 True
    2 2021-03-07 West Sorvino Binder 27 19.99 139.93 True
    3 2021-04-10 Central Andrews Pencil 66 1.99 131.34 False
    4 2021-05-14 Central Gill Pencil 53 1.29 68.37 False
    5 2021-06-17 Central Tom Desk 15 125.00 625.00 True
    6 2021-07-04 East Jones Pen Set 62 4.99 309.38 True
    7 2021-08-07 Central Tom Pen Set 42 23.95 1005.90 True
    8 2021-09-10 Central Gill Pencil 47 1.29 9.03 True
    9 2021-10-14 West Thompson Binder 57 19.99 1139.43 False
    10 2021-11-17 Central Jardine Binder 11 4.99 54.89 False
    11 2021-12-04 Central Jardine Binder 94 19.99 1879.06 False

    As you can see, both statements take in either the actual sheet name or sheet index to return the same result.

    Sometimes, we want to import all the spreadsheets stored in an Excel file into pandas DataFrames simultaneously. The good news is that the read_excel() method provides this feature for us. In order to do this, we can assign a list of sheet names or their indices to the sheet_name argument. But there is a much easier way to do the same: to assign None to the sheet_name argument. Let’s try it:

    all_sheets = pd.read_excel('sales_data.xlsx', sheet_name=None)

    Before exploring the data stored in the all_sheets variable, let’s check its data type:

    type(all_sheets)
    dict

    As you can see, the variable is a dictionary. Now, let’s reveal what is stored in this dictionary:

    for key, value in all_sheets.items():
        print(key, type(value))
    2020 <class 'pandas.core.frame.DataFrame'>
    2021 <class 'pandas.core.frame.DataFrame'>

    The code above shows that the dictionary’s keys are the Excel workbook sheet names, and its values are pandas DataFrames for each spreadsheet. To print out the content of the dictionary, we can use the following code:

    for key, value in all_sheets.items():
        print(key)
        display(value)
    2020
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2020-01-06 East Jones Pencil 95 1.99 189.05 True
    1 2020-02-09 Central Jardine Pencil 36 4.99 179.64 True
    2 2020-03-15 West Sorvino Pencil 56 2.99 167.44 True
    3 2020-04-01 East Jones Binder 60 4.99 299.40 False
    4 2020-05-05 Central Jardine Pencil 90 4.99 449.10 True
    5 2020-06-08 East Jones Binder 60 8.99 539.40 True
    6 2020-07-12 East Howard Binder 29 1.99 57.71 False
    7 2020-08-15 East Jones Pencil 35 4.99 174.65 True
    8 2020-09-01 Central Smith Desk 32 125.00 250.00 True
    9 2020-10-05 Central Morgan Binder 28 8.99 251.72 True
    10 2020-11-08 East Mike Pen 15 19.99 299.85 False
    11 2020-12-12 Central Smith Pencil 67 1.29 86.43 False
    2021
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2021-01-15 Central Gill Binder 46 8.99 413.54 True
    1 2021-02-01 Central Smith Binder 87 15.00 1305.00 True
    2 2021-03-07 West Sorvino Binder 27 19.99 139.93 True
    3 2021-04-10 Central Andrews Pencil 66 1.99 131.34 False
    4 2021-05-14 Central Gill Pencil 53 1.29 68.37 False
    5 2021-06-17 Central Tom Desk 15 125.00 625.00 True
    6 2021-07-04 East Jones Pen Set 62 4.99 309.38 True
    7 2021-08-07 Central Tom Pen Set 42 23.95 1005.90 True
    8 2021-09-10 Central Gill Pencil 47 1.29 9.03 True
    9 2021-10-14 West Thompson Binder 57 19.99 1139.43 False
    10 2021-11-17 Central Jardine Binder 11 4.99 54.89 False
    11 2021-12-04 Central Jardine Binder 94 19.99 1879.06 False

    Combining Multiple Excel Spreadsheets into a Single Pandas DataFrame

    Having one DataFrame per sheet allows us to have different columns or content in different sheets.

    But what if we prefer to store all the spreadsheets’ data in a single DataFrame? In this tutorial, the workbook spreadsheets have the same columns, so we can combine them with the concat() method of pandas.

    If you run the code below, you’ll see that the two DataFrames stored in the dictionary are concatenated:

    combined_df = pd.concat(all_sheets.values(), ignore_index=True)
    display(combined_df)
    OrderDate Region Rep Item Units Unit Cost Total Shipped
    0 2020-01-06 East Jones Pencil 95 1.99 189.05 True
    1 2020-02-09 Central Jardine Pencil 36 4.99 179.64 True
    2 2020-03-15 West Sorvino Pencil 56 2.99 167.44 True
    3 2020-04-01 East Jones Binder 60 4.99 299.40 False
    4 2020-05-05 Central Jardine Pencil 90 4.99 449.10 True
    5 2020-06-08 East Jones Binder 60 8.99 539.40 True
    6 2020-07-12 East Howard Binder 29 1.99 57.71 False
    7 2020-08-15 East Jones Pencil 35 4.99 174.65 True
    8 2020-09-01 Central Smith Desk 32 125.00 250.00 True
    9 2020-10-05 Central Morgan Binder 28 8.99 251.72 True
    10 2020-11-08 East Mike Pen 15 19.99 299.85 False
    11 2020-12-12 Central Smith Pencil 67 1.29 86.43 False
    12 2021-01-15 Central Gill Binder 46 8.99 413.54 True
    13 2021-02-01 Central Smith Binder 87 15.00 1305.00 True
    14 2021-03-07 West Sorvino Binder 27 19.99 139.93 True
    15 2021-04-10 Central Andrews Pencil 66 1.99 131.34 False
    16 2021-05-14 Central Gill Pencil 53 1.29 68.37 False
    17 2021-06-17 Central Tom Desk 15 125.00 625.00 True
    18 2021-07-04 East Jones Pen Set 62 4.99 309.38 True
    19 2021-08-07 Central Tom Pen Set 42 23.95 1005.90 True
    20 2021-09-10 Central Gill Pencil 47 1.29 9.03 True
    21 2021-10-14 West Thompson Binder 57 19.99 1139.43 False
    22 2021-11-17 Central Jardine Binder 11 4.99 54.89 False
    23 2021-12-04 Central Jardine Binder 94 19.99 1879.06 False

    Now the data stored in the combined_df DataFrame is ready for further processing or visualization. In the following piece of code, we’re going to create a simple bar chart that shows the total sales amount made by each representative. Let’s run it and see the output plot:

    total_sales_amount = combined_df.groupby('Rep').Total.sum()
    total_sales_amount.plot.bar(figsize=(10, 6))

    Output

    Reading Excel Files Using xlrd

    Although importing data into a pandas DataFrame is much more common, another helpful package for reading Excel files in Python is xlrd. In this section, we’re going to scratch the surface of how to read Excel spreadsheets using this package.


    NOTE

    The xlrd package doesn’t support xlsx files due to a potential security vulnerability. So, we use the xls version of the sales data. You can download the xls version from the link below:
    Sales Data Excel Workbook — xls ver.


    Let’s see how it works:

    import xlrd
    excel_workbook = xlrd.open_workbook('sales_data.xls')

    Above, the first line imports the xlrd package, then the open_workbook method reads the sales_data.xls file.

    We can also open an individual sheet containing the actual data. There are two ways to do so: opening a sheet by index or by name. Let’s open the first sheet by index and the second one by name:

    excel_worksheet_2020 = excel_workbook.sheet_by_index(0)
    excel_worksheet_2021 = excel_workbook.sheet_by_name('2021')

    Now, let’s see how we can print a cell value. The xlrd package provides a method called cell_value() that takes in two arguments: the cell’s row index and column index. Let’s explore it:

    print(excel_worksheet_2020.cell_value(1, 3))
    Pencil

    We can see that the cell_value function returned the value of the cell at row index 1 (the 2nd row) and column index 3 (the 4th column).
    Excel

    The xlrd package provides two helpful properties: nrows and ncols, returning the number of nonempty spreadsheet’s rows and columns respectively:

    print('Columns#:', excel_worksheet_2020.ncols)
    print('Rows#:', excel_worksheet_2020.nrows)
    Columns#: 8
    Rows#: 13

    Knowing the number of nonempty rows and columns in a spreadsheet helps us with iterating over the data using nested for loops. This makes all the Excel sheet data accessible via the cell_value() method.

    Conclusion

    This tutorial discussed how to load Excel spreadsheets into pandas DataFrames, work with multiple Excel sheets, and combine them into a single pandas DataFrame. We also explored the main aspects of the xlrd package as one of the simplest tools for accessing the Excel spreadsheets data.

    Понравилась статья? Поделить с друзьями:
  • Read excel python csv
  • Read excel parse dates
  • Read excel pandas пример
  • Read excel pandas name columns
  • Read excel pandas as text