Время на прочтение
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.
.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. Мы разобрали три различных способа с использованием трех библиотек. Все эти библиотеки имеют разные функции и свойства.
Надеемся, теперь у вас не возникнет сложностей с чтением этих файлов в ваших скриптах.
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.active
Code language: Python (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.
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 Path
Code language: Python (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)
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)
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.active
Code language: Python (python)
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)
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 Path
Code 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))
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).
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.
pyexcel — Let you focus on data, instead of file formats
Support the project
If your company has embedded pyexcel and its components into a revenue generating
product, please support me on github, patreon
or bounty source to maintain
the project and develop it further.
If you are an individual, you are welcome to support me too and for however long
you feel like. As my backer, you will receive
early access to pyexcel related contents.
And your issues will get prioritized if you would like to become my patreon as pyexcel pro user.
With your financial support, I will be able to invest
a little bit more time in coding, documentation and writing interesting posts.
Known constraints
Fonts, colors and charts are not supported.
Nor to read password protected xls, xlsx and ods files.
Introduction
Feature Highlights
A list of supported file formats
file format | definition |
---|---|
csv | comma separated values |
tsv | tab separated values |
csvz | a zip file that contains one or many csv files |
tsvz | a zip file that contains one or many tsv files |
xls | a spreadsheet file format created by MS-Excel 97-2003 |
xlsx | MS-Excel Extensions to the Office Open XML SpreadsheetML File Format. |
xlsm | an MS-Excel Macro-Enabled Workbook file |
ods | open document spreadsheet |
fods | flat open document spreadsheet |
json | java script object notation |
html | html table of the data structure |
simple | simple presentation |
rst | rStructured Text presentation of the data |
mediawiki | media wiki table |
- One application programming interface(API) to handle multiple data sources:
- physical file
- memory file
- SQLAlchemy table
- Django Model
- Python data structures: dictionary, records and array
- One API to read and write data in various excel file formats.
- For large data sets, data streaming are supported. A genenerator can be returned to you. Checkout iget_records, iget_array, isave_as and isave_book_as.
Installation
You can install pyexcel via pip:
or clone it and install it:
$ git clone https://github.com/pyexcel/pyexcel.git
$ cd pyexcel
$ python setup.py install
One liners
This section shows you how to get data from your excel files and how to
export data to excel files in one line
Read from the excel files
Get a list of dictionaries
Suppose you want to process History of Classical Music:
History of Classical Music:
Name | Period | Representative Composers |
Medieval | c.1150-c.1400 | Machaut, Landini |
Renaissance | c.1400-c.1600 | Gibbons, Frescobaldi |
Baroque | c.1600-c.1750 | JS Bach, Vivaldi |
Classical | c.1750-c.1830 | Joseph Haydn, Wolfgan Amadeus Mozart |
Early Romantic | c.1830-c.1860 | Chopin, Mendelssohn, Schumann, Liszt |
Late Romantic | c.1860-c.1920 | Wagner,Verdi |
Modernist | 20th century | Sergei Rachmaninoff,Calude Debussy |
Let’s get a list of dictionary out from the xls file:
>>> records = p.get_records(file_name="your_file.xls")
And let’s check what do we have:
>>> for row in records: ... print(f"{row['Representative Composers']} are from {row['Name']} period ({row['Period']})") Machaut, Landini are from Medieval period (c.1150-c.1400) Gibbons, Frescobaldi are from Renaissance period (c.1400-c.1600) JS Bach, Vivaldi are from Baroque period (c.1600-c.1750) Joseph Haydn, Wolfgan Amadeus Mozart are from Classical period (c.1750-c.1830) Chopin, Mendelssohn, Schumann, Liszt are from Early Romantic period (c.1830-c.1860) Wagner,Verdi are from Late Romantic period (c.1860-c.1920) Sergei Rachmaninoff,Calude Debussy are from Modernist period (20th century)
Get two dimensional array
Instead, what if you have to use pyexcel.get_array to do the same:
>>> for row in p.get_array(file_name="your_file.xls", start_row=1): ... print(f"{row[2]} are from {row[0]} period ({row[1]})") Machaut, Landini are from Medieval period (c.1150-c.1400) Gibbons, Frescobaldi are from Renaissance period (c.1400-c.1600) JS Bach, Vivaldi are from Baroque period (c.1600-c.1750) Joseph Haydn, Wolfgan Amadeus Mozart are from Classical period (c.1750-c.1830) Chopin, Mendelssohn, Schumann, Liszt are from Early Romantic period (c.1830-c.1860) Wagner,Verdi are from Late Romantic period (c.1860-c.1920) Sergei Rachmaninoff,Calude Debussy are from Modernist period (20th century)
where start_row skips the header row.
Get a dictionary
You can get a dictionary too:
>>> my_dict = p.get_dict(file_name="your_file.xls", name_columns_by_row=0)
And let’s have a look inside:
>>> from pyexcel._compact import OrderedDict >>> isinstance(my_dict, OrderedDict) True >>> for key, values in my_dict.items(): ... print(key + " : " + ','.join([str(item) for item in values])) Name : Medieval,Renaissance,Baroque,Classical,Early Romantic,Late Romantic,Modernist Period : c.1150-c.1400,c.1400-c.1600,c.1600-c.1750,c.1750-c.1830,c.1830-c.1860,c.1860-c.1920,20th century Representative Composers : Machaut, Landini,Gibbons, Frescobaldi,JS Bach, Vivaldi,Joseph Haydn, Wolfgan Amadeus Mozart,Chopin, Mendelssohn, Schumann, Liszt,Wagner,Verdi,Sergei Rachmaninoff,Calude Debussy
Please note that my_dict is an OrderedDict.
Get a dictionary of two dimensional array
Suppose you have a multiple sheet book as the following:
Top Violinist:
Name | Period | Nationality |
Antonio Vivaldi | 1678-1741 | Italian |
Niccolo Paganini | 1782-1840 | Italian |
Pablo de Sarasate | 1852-1904 | Spainish |
Eugene Ysaye | 1858-1931 | Belgian |
Fritz Kreisler | 1875-1962 | Astria-American |
Jascha Heifetz | 1901-1987 | Russian-American |
David Oistrakh | 1908-1974 | Russian |
Yehundi Menuhin | 1916-1999 | American |
Itzhak Perlman | 1945- | Israeli-American |
Hilary Hahn | 1979- | American |
Noteable Violin Makers:
Maker | Period | Country |
Antonio Stradivari | 1644-1737 | Cremona, Italy |
Giovanni Paolo Maggini | 1580-1630 | Botticino, Italy |
Amati Family | 1500-1740 | Cremona, Italy |
Guarneri Family | 1626-1744 | Cremona, Italy |
Rugeri Family | 1628-1719 | Cremona, Italy |
Carlo Bergonzi | 1683-1747 | Cremona, Italy |
Jacob Stainer | 1617-1683 | Austria |
Most Expensive Violins:
Name | Estimated Value | Location |
Messiah Stradivarious | $ 20,000,000 | Ashmolean Museum in Oxford, England |
Vieuxtemps Guarneri | $ 16,000,000 | On loan to Anne Akiko Meyers |
Lady Blunt | $ 15,900,000 | Anonymous bidder |
Here is the code to obtain those sheets as a single dictionary:
>>> book_dict = p.get_book_dict(file_name="book.xls")
And check:
>>> isinstance(book_dict, OrderedDict) True >>> import json >>> for key, item in book_dict.items(): ... print(json.dumps({key: item})) {"Most Expensive Violins": [["Name", "Estimated Value", "Location"], ["Messiah Stradivarious", "$ 20,000,000", "Ashmolean Museum in Oxford, England"], ["Vieuxtemps Guarneri", "$ 16,000,000", "On loan to Anne Akiko Meyers"], ["Lady Blunt", "$ 15,900,000", "Anonymous bidder"]]} {"Noteable Violin Makers": [["Maker", "Period", "Country"], ["Antonio Stradivari", "1644-1737", "Cremona, Italy"], ["Giovanni Paolo Maggini", "1580-1630", "Botticino, Italy"], ["Amati Family", "1500-1740", "Cremona, Italy"], ["Guarneri Family", "1626-1744", "Cremona, Italy"], ["Rugeri Family", "1628-1719", "Cremona, Italy"], ["Carlo Bergonzi", "1683-1747", "Cremona, Italy"], ["Jacob Stainer", "1617-1683", "Austria"]]} {"Top Violinist": [["Name", "Period", "Nationality"], ["Antonio Vivaldi", "1678-1741", "Italian"], ["Niccolo Paganini", "1782-1840", "Italian"], ["Pablo de Sarasate", "1852-1904", "Spainish"], ["Eugene Ysaye", "1858-1931", "Belgian"], ["Fritz Kreisler", "1875-1962", "Astria-American"], ["Jascha Heifetz", "1901-1987", "Russian-American"], ["David Oistrakh", "1908-1974", "Russian"], ["Yehundi Menuhin", "1916-1999", "American"], ["Itzhak Perlman", "1945-", "Israeli-American"], ["Hilary Hahn", "1979-", "American"]]}
Write data
Export an array
Suppose you have the following array:
>>> data = [['G', 'D', 'A', 'E'], ['Thomastik-Infield Domaints', 'Thomastik-Infield Domaints', 'Thomastik-Infield Domaints', 'Pirastro'], ['Silver wound', '', 'Aluminum wound', 'Gold Label Steel']]
And here is the code to save it as an excel file :
>>> p.save_as(array=data, dest_file_name="example.xls")
Let’s verify it:
>>> p.get_sheet(file_name="example.xls") pyexcel_sheet1: +----------------------------+----------------------------+----------------------------+------------------+ | G | D | A | E | +----------------------------+----------------------------+----------------------------+------------------+ | Thomastik-Infield Domaints | Thomastik-Infield Domaints | Thomastik-Infield Domaints | Pirastro | +----------------------------+----------------------------+----------------------------+------------------+ | Silver wound | | Aluminum wound | Gold Label Steel | +----------------------------+----------------------------+----------------------------+------------------+
And here is the code to save it as a csv file :
>>> p.save_as(array=data, ... dest_file_name="example.csv", ... dest_delimiter=':')
Let’s verify it:
>>> with open("example.csv") as f: ... for line in f.readlines(): ... print(line.rstrip()) ... G:D:A:E Thomastik-Infield Domaints:Thomastik-Infield Domaints:Thomastik-Infield Domaints:Pirastro Silver wound::Aluminum wound:Gold Label Steel
Export a list of dictionaries
>>> records = [ ... {"year": 1903, "country": "Germany", "speed": "206.7km/h"}, ... {"year": 1964, "country": "Japan", "speed": "210km/h"}, ... {"year": 2008, "country": "China", "speed": "350km/h"} ... ] >>> p.save_as(records=records, dest_file_name='high_speed_rail.xls')
Export a dictionary of single key value pair
>>> henley_on_thames_facts = { ... "area": "5.58 square meters", ... "population": "11,619", ... "civial parish": "Henley-on-Thames", ... "latitude": "51.536", ... "longitude": "-0.898" ... } >>> p.save_as(adict=henley_on_thames_facts, dest_file_name='henley.xlsx')
Export a dictionary of single dimensonal array
>>> ccs_insights = { ... "year": ["2017", "2018", "2019", "2020", "2021"], ... "smart phones": [1.53, 1.64, 1.74, 1.82, 1.90], ... "feature phones": [0.46, 0.38, 0.30, 0.23, 0.17] ... } >>> p.save_as(adict=ccs_insights, dest_file_name='ccs.csv')
Export a dictionary of two dimensional array as a book
Suppose you want to save the below dictionary to an excel file :
>>> a_dictionary_of_two_dimensional_arrays = { ... 'Sheet 1': ... [ ... [1.0, 2.0, 3.0], ... [4.0, 5.0, 6.0], ... [7.0, 8.0, 9.0] ... ], ... 'Sheet 2': ... [ ... ['X', 'Y', 'Z'], ... [1.0, 2.0, 3.0], ... [4.0, 5.0, 6.0] ... ], ... 'Sheet 3': ... [ ... ['O', 'P', 'Q'], ... [3.0, 2.0, 1.0], ... [4.0, 3.0, 2.0] ... ] ... }
Here is the code:
>>> p.save_book_as( ... bookdict=a_dictionary_of_two_dimensional_arrays, ... dest_file_name="book.xls" ... )
If you want to preserve the order of sheets in your dictionary, you have to
pass on an ordered dictionary to the function itself. For example:
>>> data = OrderedDict() >>> data.update({"Sheet 2": a_dictionary_of_two_dimensional_arrays['Sheet 2']}) >>> data.update({"Sheet 1": a_dictionary_of_two_dimensional_arrays['Sheet 1']}) >>> data.update({"Sheet 3": a_dictionary_of_two_dimensional_arrays['Sheet 3']}) >>> p.save_book_as(bookdict=data, dest_file_name="book.xls")
Let’s verify its order:
>>> book_dict = p.get_book_dict(file_name="book.xls") >>> for key, item in book_dict.items(): ... print(json.dumps({key: item})) {"Sheet 2": [["X", "Y", "Z"], [1, 2, 3], [4, 5, 6]]} {"Sheet 1": [[1, 2, 3], [4, 5, 6], [7, 8, 9]]} {"Sheet 3": [["O", "P", "Q"], [3, 2, 1], [4, 3, 2]]}
Please notice that «Sheet 2» is the first item in the book_dict, meaning the order of sheets are preserved.
Transcoding
Note
Please note that pyexcel-cli can perform file transcoding at command line.
No need to open your editor, save the problem, then python run.
The following code does a simple file format transcoding from xls to csv:
>>> p.save_as(file_name="birth.xls", dest_file_name="birth.csv")
Again it is really simple. Let’s verify what we have gotten:
>>> sheet = p.get_sheet(file_name="birth.csv") >>> sheet birth.csv: +-------+--------+----------+ | name | weight | birth | +-------+--------+----------+ | Adam | 3.4 | 03/02/15 | +-------+--------+----------+ | Smith | 4.2 | 12/11/14 | +-------+--------+----------+
Note
Please note that csv(comma separate value) file is pure text file. Formula, charts, images and formatting in xls file will disappear no matter which transcoding tool you use. Hence, pyexcel is a quick alternative for this transcoding job.
Let use previous example and save it as xlsx instead
>>> p.save_as(file_name="birth.xls", ... dest_file_name="birth.xlsx") # change the file extension
Again let’s verify what we have gotten:
>>> sheet = p.get_sheet(file_name="birth.xlsx") >>> sheet pyexcel_sheet1: +-------+--------+----------+ | name | weight | birth | +-------+--------+----------+ | Adam | 3.4 | 03/02/15 | +-------+--------+----------+ | Smith | 4.2 | 12/11/14 | +-------+--------+----------+
Excel book merge and split operation in one line
Merge all excel files in directory into a book where each file become a sheet
The following code will merge every excel files into one file, say «output.xls»:
from pyexcel.cookbook import merge_all_to_a_book import glob merge_all_to_a_book(glob.glob("your_csv_directory*.csv"), "output.xls")
You can mix and match with other excel formats: xls, xlsm and ods. For example, if you are sure you have only xls, xlsm, xlsx, ods and csv files in your_excel_file_directory, you can do the following:
from pyexcel.cookbook import merge_all_to_a_book import glob merge_all_to_a_book(glob.glob("your_excel_file_directory*.*"), "output.xls")
Split a book into single sheet files
Suppose you have many sheets in a work book and you would like to separate each into a single sheet excel file. You can easily do this:
>>> from pyexcel.cookbook import split_a_book >>> split_a_book("megabook.xls", "output.xls") >>> import glob >>> outputfiles = glob.glob("*_output.xls") >>> for file in sorted(outputfiles): ... print(file) ... Sheet 1_output.xls Sheet 2_output.xls Sheet 3_output.xls
for the output file, you can specify any of the supported formats
Extract just one sheet from a book
Suppose you just want to extract one sheet from many sheets that exists in a work book and you would like to separate it into a single sheet excel file. You can easily do this:
>>> from pyexcel.cookbook import extract_a_sheet_from_a_book >>> extract_a_sheet_from_a_book("megabook.xls", "Sheet 1", "output.xls") >>> if os.path.exists("Sheet 1_output.xls"): ... print("Sheet 1_output.xls exists") ... Sheet 1_output.xls exists
for the output file, you can specify any of the supported formats
Hidden feature: partial read
Most pyexcel users do not know, but other library users were requesting partial read
When you are dealing with huge amount of data, e.g. 64GB, obviously you would not
like to fill up your memory with those data. What you may want to do is, record
data from Nth line, take M records and stop. And you only want to use your memory
for the M records, not for beginning part nor for the tail part.
Hence partial read feature is developed to read partial data into memory for
processing.
You can paginate by row, by column and by both, hence you dictate what portion of the
data to read back. But remember only row limit features help you save memory. Let’s
you use this feature to record data from Nth column, take M number of columns and skip
the rest. You are not going to reduce your memory footprint.
Why did not I see above benefit?
This feature depends heavily on the implementation details.
pyexcel-xls (xlrd), pyexcel-xlsx (openpyxl), pyexcel-ods (odfpy) and
pyexcel-ods3 (pyexcel-ezodf) will read all data into memory. Because xls,
xlsx and ods file are effective a zipped folder, all four will unzip the folder
and read the content in xml format in full, so as to make sense of all details.
Hence, during the partial data is been returned, the memory consumption won’t
differ from reading the whole data back. Only after the partial
data is returned, the memory comsumption curve shall jump the cliff. So pagination
code here only limits the data returned to your program.
With that said, pyexcel-xlsxr, pyexcel-odsr and pyexcel-htmlr DOES read
partial data into memory. Those three are implemented in such a way that they
consume the xml(html) when needed. When they have read designated portion of the
data, they stop, even if they are half way through.
In addition, pyexcel’s csv readers can read partial data into memory too.
Let’s assume the following file is a huge csv file:
>>> import datetime >>> import pyexcel as pe >>> data = [ ... [1, 21, 31], ... [2, 22, 32], ... [3, 23, 33], ... [4, 24, 34], ... [5, 25, 35], ... [6, 26, 36] ... ] >>> pe.save_as(array=data, dest_file_name="your_file.csv")
And let’s pretend to read partial data:
>>> pe.get_sheet(file_name="your_file.csv", start_row=2, row_limit=3) your_file.csv: +---+----+----+ | 3 | 23 | 33 | +---+----+----+ | 4 | 24 | 34 | +---+----+----+ | 5 | 25 | 35 | +---+----+----+
And you could as well do the same for columns:
>>> pe.get_sheet(file_name="your_file.csv", start_column=1, column_limit=2) your_file.csv: +----+----+ | 21 | 31 | +----+----+ | 22 | 32 | +----+----+ | 23 | 33 | +----+----+ | 24 | 34 | +----+----+ | 25 | 35 | +----+----+ | 26 | 36 | +----+----+
Obvious, you could do both at the same time:
>>> pe.get_sheet(file_name="your_file.csv", ... start_row=2, row_limit=3, ... start_column=1, column_limit=2) your_file.csv: +----+----+ | 23 | 33 | +----+----+ | 24 | 34 | +----+----+ | 25 | 35 | +----+----+
The pagination support is available across all pyexcel plugins.
Note
No column pagination support for query sets as data source.
Formatting while transcoding a big data file
If you are transcoding a big data set, conventional formatting method would not
help unless a on-demand free RAM is available. However, there is a way to minimize
the memory footprint of pyexcel while the formatting is performed.
Let’s continue from previous example. Suppose we want to transcode «your_file.csv»
to «your_file.xls» but increase each element by 1.
What we can do is to define a row renderer function as the following:
>>> def increment_by_one(row): ... for element in row: ... yield element + 1
Then pass it onto save_as function using row_renderer:
>>> pe.isave_as(file_name="your_file.csv", ... row_renderer=increment_by_one, ... dest_file_name="your_file.xlsx")
Note
If the data content is from a generator, isave_as has to be used.
We can verify if it was done correctly:
>>> pe.get_sheet(file_name="your_file.xlsx") your_file.csv: +---+----+----+ | 2 | 22 | 32 | +---+----+----+ | 3 | 23 | 33 | +---+----+----+ | 4 | 24 | 34 | +---+----+----+ | 5 | 25 | 35 | +---+----+----+ | 6 | 26 | 36 | +---+----+----+ | 7 | 27 | 37 | +---+----+----+
Stream APIs for big file : A set of two liners
When you are dealing with BIG excel files, you will want pyexcel to use
constant memory.
This section shows you how to get data from your BIG excel files and how to
export data to excel files in two lines at most, without eating all
your computer memory.
Two liners for get data from big excel files
Get a list of dictionaries
Suppose you want to process the following coffee data again:
Top 5 coffeine drinks:
Coffees | Serving Size | Caffeine (mg) |
Starbucks Coffee Blonde Roast | venti(20 oz) | 475 |
Dunkin’ Donuts Coffee with Turbo Shot | large(20 oz.) | 398 |
Starbucks Coffee Pike Place Roast | grande(16 oz.) | 310 |
Panera Coffee Light Roast | regular(16 oz.) | 300 |
Let’s get a list of dictionary out from the xls file:
>>> records = p.iget_records(file_name="your_file.xls")
And let’s check what do we have:
>>> for r in records: ... print(f"{r['Serving Size']} of {r['Coffees']} has {r['Caffeine (mg)']} mg") venti(20 oz) of Starbucks Coffee Blonde Roast has 475 mg large(20 oz.) of Dunkin' Donuts Coffee with Turbo Shot has 398 mg grande(16 oz.) of Starbucks Coffee Pike Place Roast has 310 mg regular(16 oz.) of Panera Coffee Light Roast has 300 mg
Please do not forgot the second line to close the opened file handle:
Get two dimensional array
Instead, what if you have to use pyexcel.get_array to do the same:
>>> for row in p.iget_array(file_name="your_file.xls", start_row=1): ... print(f"{row[1]} of {row[0]} has {row[2]} mg") venti(20 oz) of Starbucks Coffee Blonde Roast has 475 mg large(20 oz.) of Dunkin' Donuts Coffee with Turbo Shot has 398 mg grande(16 oz.) of Starbucks Coffee Pike Place Roast has 310 mg regular(16 oz.) of Panera Coffee Light Roast has 300 mg
Again, do not forgot the second line:
where start_row skips the header row.
Data export in one liners
Export an array
Suppose you have the following array:
>>> data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
And here is the code to save it as an excel file :
>>> p.isave_as(array=data, dest_file_name="example.xls")
But the following line is not required because the data source
are not file sources:
Let’s verify it:
>>> p.get_sheet(file_name="example.xls") pyexcel_sheet1: +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 7 | 8 | 9 | +---+---+---+
And here is the code to save it as a csv file :
>>> p.isave_as(array=data, ... dest_file_name="example.csv", ... dest_delimiter=':')
Let’s verify it:
>>> with open("example.csv") as f: ... for line in f.readlines(): ... print(line.rstrip()) ... 1:2:3 4:5:6 7:8:9
Export a list of dictionaries
>>> records = [ ... {"year": 1903, "country": "Germany", "speed": "206.7km/h"}, ... {"year": 1964, "country": "Japan", "speed": "210km/h"}, ... {"year": 2008, "country": "China", "speed": "350km/h"} ... ] >>> p.isave_as(records=records, dest_file_name='high_speed_rail.xls')
Export a dictionary of single key value pair
>>> henley_on_thames_facts = { ... "area": "5.58 square meters", ... "population": "11,619", ... "civial parish": "Henley-on-Thames", ... "latitude": "51.536", ... "longitude": "-0.898" ... } >>> p.isave_as(adict=henley_on_thames_facts, dest_file_name='henley.xlsx')
Export a dictionary of single dimensonal array
>>> ccs_insights = { ... "year": ["2017", "2018", "2019", "2020", "2021"], ... "smart phones": [1.53, 1.64, 1.74, 1.82, 1.90], ... "feature phones": [0.46, 0.38, 0.30, 0.23, 0.17] ... } >>> p.isave_as(adict=ccs_insights, dest_file_name='ccs.csv') >>> p.free_resources()
Export a dictionary of two dimensional array as a book
Suppose you want to save the below dictionary to an excel file :
>>> a_dictionary_of_two_dimensional_arrays = { ... 'Sheet 1': ... [ ... [1.0, 2.0, 3.0], ... [4.0, 5.0, 6.0], ... [7.0, 8.0, 9.0] ... ], ... 'Sheet 2': ... [ ... ['X', 'Y', 'Z'], ... [1.0, 2.0, 3.0], ... [4.0, 5.0, 6.0] ... ], ... 'Sheet 3': ... [ ... ['O', 'P', 'Q'], ... [3.0, 2.0, 1.0], ... [4.0, 3.0, 2.0] ... ] ... }
Here is the code:
>>> p.isave_book_as( ... bookdict=a_dictionary_of_two_dimensional_arrays, ... dest_file_name="book.xls" ... )
If you want to preserve the order of sheets in your dictionary, you have to
pass on an ordered dictionary to the function itself. For example:
>>> from pyexcel._compact import OrderedDict >>> data = OrderedDict() >>> data.update({"Sheet 2": a_dictionary_of_two_dimensional_arrays['Sheet 2']}) >>> data.update({"Sheet 1": a_dictionary_of_two_dimensional_arrays['Sheet 1']}) >>> data.update({"Sheet 3": a_dictionary_of_two_dimensional_arrays['Sheet 3']}) >>> p.isave_book_as(bookdict=data, dest_file_name="book.xls") >>> p.free_resources()
Let’s verify its order:
>>> import json >>> book_dict = p.get_book_dict(file_name="book.xls") >>> for key, item in book_dict.items(): ... print(json.dumps({key: item})) {"Sheet 2": [["X", "Y", "Z"], [1, 2, 3], [4, 5, 6]]} {"Sheet 1": [[1, 2, 3], [4, 5, 6], [7, 8, 9]]} {"Sheet 3": [["O", "P", "Q"], [3, 2, 1], [4, 3, 2]]}
Please notice that «Sheet 2» is the first item in the book_dict, meaning the order of sheets are preserved.
File format transcoding on one line
Note
Please note that the following file transcoding could be with zero line. Please
install pyexcel-cli and you will do the transcode in one command. No need to
open your editor, save the problem, then python run.
The following code does a simple file format transcoding from xls to csv:
>>> import pyexcel >>> p.save_as(file_name="birth.xls", dest_file_name="birth.csv")
Again it is really simple. Let’s verify what we have gotten:
>>> sheet = p.get_sheet(file_name="birth.csv") >>> sheet birth.csv: +-------+--------+----------+ | name | weight | birth | +-------+--------+----------+ | Adam | 3.4 | 03/02/15 | +-------+--------+----------+ | Smith | 4.2 | 12/11/14 | +-------+--------+----------+
Note
Please note that csv(comma separate value) file is pure text file. Formula, charts, images and formatting in xls file will disappear no matter which transcoding tool you use. Hence, pyexcel is a quick alternative for this transcoding job.
Let use previous example and save it as xlsx instead
>>> import pyexcel >>> p.isave_as(file_name="birth.xls", ... dest_file_name="birth.xlsx") # change the file extension
Again let’s verify what we have gotten:
>>> sheet = p.get_sheet(file_name="birth.xlsx") >>> sheet pyexcel_sheet1: +-------+--------+----------+ | name | weight | birth | +-------+--------+----------+ | Adam | 3.4 | 03/02/15 | +-------+--------+----------+ | Smith | 4.2 | 12/11/14 | +-------+--------+----------+
Available Plugins
A list of file formats supported by external plugins
Package name | Supported file formats | Dependencies |
---|---|---|
pyexcel-io | csv, csvz [1], tsv, tsvz [2] |
|
pyexcel-xls | xls, xlsx(read only), xlsm(read only) |
xlrd, xlwt |
pyexcel-xlsx | xlsx | openpyxl |
pyexcel-ods3 | ods | pyexcel-ezodf, lxml |
pyexcel-ods | ods | odfpy |
Dedicated file reader and writers
Package name | Supported file formats | Dependencies |
---|---|---|
pyexcel-xlsxw | xlsx(write only) | XlsxWriter |
pyexcel-libxlsxw | xlsx(write only) | libxlsxwriter |
pyexcel-xlsxr | xlsx(read only) | lxml |
pyexcel-xlsbr | xlsb(read only) | pyxlsb |
pyexcel-odsr | read only for ods, fods | lxml |
pyexcel-odsw | write only for ods | loxun |
pyexcel-htmlr | html(read only) | lxml,html5lib |
pyexcel-pdfr | pdf(read only) | camelot |
Plugin shopping guide
Since 2020, all pyexcel-io plugins have dropped the support for python versions
which are lower than 3.6. If you want to use any of those Python versions, please use pyexcel-io
and its plugins versions that are lower than 0.6.0.
Except csv files, xls, xlsx and ods files are a zip of a folder containing a lot of
xml files
The dedicated readers for excel files can stream read
In order to manage the list of plugins installed, you need to use pip to add or remove
a plugin. When you use virtualenv, you can have different plugins per virtual
environment. In the situation where you have multiple plugins that does the same thing
in your environment, you need to tell pyexcel which plugin to use per function call.
For example, pyexcel-ods and pyexcel-odsr, and you want to get_array to use pyexcel-odsr.
You need to append get_array(…, library=’pyexcel-odsr’).
Other data renderers
Package name | Supported file formats | Dependencies | Python versions |
---|---|---|---|
pyexcel-text | write only:rst, mediawiki, html, latex, grid, pipe, orgtbl, plain simple read only: ndjson r/w: json |
tabulate | 2.6, 2.7, 3.3, 3.4 3.5, 3.6, pypy |
pyexcel-handsontable | handsontable in html | handsontable | same as above |
pyexcel-pygal | svg chart | pygal | 2.7, 3.3, 3.4, 3.5 3.6, pypy |
pyexcel-sortable | sortable table in html | csvtotable | same as above |
pyexcel-gantt | gantt chart in html | frappe-gantt | except pypy, same as above |
Footnotes
Acknowledgement
All great work have been done by odf, ezodf, xlrd, xlwt, tabulate and other
individual developers. This library unites only the data access code.
License
New BSD License
You all must have worked with Excel at some time in your life and must have felt the need for automating some repetitive or tedious task. Don’t worry in this tutorial we are going to learn about how to work with Excel using Python, or automating Excel using Python. We will be covering this with the help of the Openpyxl module.
Getting Started
Openpyxl is a Python library that provides various methods to interact with Excel Files using Python. It allows operations like reading, writing, arithmetic operations, plotting graphs, etc.
This module does not come in-built with Python. To install this type the below command in the terminal.
pip install openpyxl
Reading from Spreadsheets
To read an Excel file you have to open the spreadsheet using the load_workbook() method. After that, you can use the active to select the first sheet available and the cell attribute to select the cell by passing the row and column parameter. The value attribute prints the value of the particular cell. See the below example to get a better understanding.
Note: The first row or column integer is 1, not 0.
Dataset Used: It can be downloaded from here.
Example:
Python3
import
openpyxl
path
=
"gfg.xlsx"
wb_obj
=
openpyxl.load_workbook(path)
sheet_obj
=
wb_obj.active
cell_obj
=
sheet_obj.cell(row
=
1
, column
=
1
)
print
(cell_obj.value)
Output:
Name
Reading from Multiple Cells
There can be two ways of reading from multiple cells.
Method 1: We can get the count of the total rows and columns using the max_row and max_column respectively. We can use these values inside the for loop to get the value of the desired row or column or any cell depending upon the situation. Let’s see how to get the value of the first column and first row.
Example:
Python3
import
openpyxl
path
=
"gfg.xlsx"
wb_obj
=
openpyxl.load_workbook(path)
sheet_obj
=
wb_obj.active
row
=
sheet_obj.max_row
column
=
sheet_obj.max_column
print
(
"Total Rows:"
, row)
print
(
"Total Columns:"
, column)
print
(
"nValue of first column"
)
for
i
in
range
(
1
, row
+
1
):
cell_obj
=
sheet_obj.cell(row
=
i, column
=
1
)
print
(cell_obj.value)
print
(
"nValue of first row"
)
for
i
in
range
(
1
, column
+
1
):
cell_obj
=
sheet_obj.cell(row
=
2
, column
=
i)
print
(cell_obj.value, end
=
" "
)
Output:
Total Rows: 6 Total Columns: 4 Value of first column Name Ankit Rahul Priya Nikhil Nisha Value of first row Ankit B.Tech CSE 4
Method 2: We can also read from multiple cells using the cell name. This can be seen as the list slicing of Python.
Python3
import
openpyxl
path
=
"gfg.xlsx"
wb_obj
=
openpyxl.load_workbook(path)
sheet_obj
=
wb_obj.active
cell_obj
=
sheet_obj[
'A1'
:
'B6'
]
for
cell1, cell2
in
cell_obj:
print
(cell1.value, cell2.value)
Output:
Name Course Ankit B.Tech Rahul M.Tech Priya MBA Nikhil B.Tech Nisha B.Tech
Refer to the below article to get detailed information about reading excel files using openpyxl.
- Reading an excel file using Python openpyxl module
Writing to Spreadsheets
First, let’s create a new spreadsheet, and then we will write some data to the newly created file. An empty spreadsheet can be created using the Workbook() method. Let’s see the below example.
Example:
Python3
from
openpyxl
import
Workbook
workbook
=
Workbook()
workbook.save(filename
=
"sample.xlsx"
)
Output:
After creating an empty file, let’s see how to add some data to it using Python. To add data first we need to select the active sheet and then using the cell() method we can select any particular cell by passing the row and column number as its parameter. We can also write using cell names. See the below example for a better understanding.
Example:
Python3
import
openpyxl
wb
=
openpyxl.Workbook()
sheet
=
wb.active
c1
=
sheet.cell(row
=
1
, column
=
1
)
c1.value
=
"Hello"
c2
=
sheet.cell(row
=
1
, column
=
2
)
c2.value
=
"World"
c3
=
sheet[
'A2'
]
c3.value
=
"Welcome"
c4
=
sheet[
'B2'
]
c4.value
=
"Everyone"
wb.save(
"sample.xlsx"
)
Output:
Refer to the below article to get detailed information about writing to excel.
- Writing to an excel file using openpyxl module
Appending to the Spreadsheet
In the above example, you will see that every time you try to write to a spreadsheet the existing data gets overwritten, and the file is saved as a new file. This happens because the Workbook() method always creates a new workbook file object. To write to an existing workbook you must open the file with the load_workbook() method. We will use the above-created workbook.
Example:
Python3
import
openpyxl
wb
=
openpyxl.load_workbook(
"sample.xlsx"
)
sheet
=
wb.active
c
=
sheet[
'A3'
]
c.value
=
"New Data"
wb.save(
"sample.xlsx"
)
Output:
We can also use the append() method to append multiple data at the end of the sheet.
Example:
Python3
import
openpyxl
wb
=
openpyxl.load_workbook(
"sample.xlsx"
)
sheet
=
wb.active
data
=
(
(
1
,
2
,
3
),
(
4
,
5
,
6
)
)
for
row
in
data:
sheet.append(row)
wb.save(
'sample.xlsx'
)
Output:
Arithmetic Operation on Spreadsheet
Arithmetic operations can be performed by typing the formula in a particular cell of the spreadsheet. For example, if we want to find the sum then =Sum() formula of the excel file is used.
Example:
Python3
import
openpyxl
wb
=
openpyxl.Workbook()
sheet
=
wb.active
sheet[
'A1'
]
=
200
sheet[
'A2'
]
=
300
sheet[
'A3'
]
=
400
sheet[
'A4'
]
=
500
sheet[
'A5'
]
=
600
sheet[
'A7'
]
=
'= SUM(A1:A5)'
wb.save(
"sum.xlsx"
)
Output:
Refer to the below article to get detailed information about the Arithmetic operations on Spreadsheet.
- Arithmetic operations in excel file using openpyxl
Adjusting Rows and Column
Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimensions contains ColumnDimension objects. In row_dimensions, one can access one of the objects using the number of the row (in this case, 1 or 2). In column_dimensions, one can access one of the objects using the letter of the column (in this case, A or B).
Example:
Python3
import
openpyxl
wb
=
openpyxl.Workbook()
sheet
=
wb.active
sheet.cell(row
=
1
, column
=
1
).value
=
' hello '
sheet.cell(row
=
2
, column
=
2
).value
=
' everyone '
sheet.row_dimensions[
1
].height
=
70
sheet.column_dimensions[
'B'
].width
=
20
wb.save(
'sample.xlsx'
)
Output:
Merging Cells
A rectangular area of cells can be merged into a single cell with the merge_cells() sheet method. The argument to merge_cells() is a single string of the top-left and bottom-right cells of the rectangular area to be merged.
Example:
Python3
import
openpyxl
wb
=
openpyxl.Workbook()
sheet
=
wb.active
sheet.merge_cells(
'A2:D4'
)
sheet.cell(row
=
2
, column
=
1
).value
=
'Twelve cells join together.'
sheet.merge_cells(
'C6:D6'
)
sheet.cell(row
=
6
, column
=
6
).value
=
'Two merge cells.'
wb.save(
'sample.xlsx'
)
Output:
Unmerging Cells
To unmerge cells, call the unmerge_cells() sheet method.
Example:
Python3
import
openpyxl
wb
=
openpyxl.load_workbook(
'sample.xlsx'
)
sheet
=
wb.active
sheet.unmerge_cells(
'A2:D4'
)
sheet.unmerge_cells(
'C6:D6'
)
wb.save(
'sample.xlsx'
)
Output:
Setting Font Style
To customize font styles in cells, important, import the Font() function from the openpyxl.styles module.
Example:
Python3
import
openpyxl
from
openpyxl.styles
import
Font
wb
=
openpyxl.Workbook()
sheet
=
wb.active
sheet.cell(row
=
1
, column
=
1
).value
=
"GeeksforGeeks"
sheet.cell(row
=
1
, column
=
1
).font
=
Font(size
=
24
)
sheet.cell(row
=
2
, column
=
2
).value
=
"GeeksforGeeks"
sheet.cell(row
=
2
, column
=
2
).font
=
Font(size
=
24
, italic
=
True
)
sheet.cell(row
=
3
, column
=
3
).value
=
"GeeksforGeeks"
sheet.cell(row
=
3
, column
=
3
).font
=
Font(size
=
24
, bold
=
True
)
sheet.cell(row
=
4
, column
=
4
).value
=
"GeeksforGeeks"
sheet.cell(row
=
4
, column
=
4
).font
=
Font(size
=
24
, name
=
'Times New Roman'
)
wb.save(
'sample.xlsx'
)
Output:
Refer to the below article to get detailed information about adjusting rows and columns.
- Adjusting rows and columns of an excel file using openpyxl module
Plotting Charts
Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart objects of specific chart class( i.e BarChart, LineChart, etc.). After creating chart objects, insert data in it, and lastly, add that chart object in the sheet object.
Example 1:
Python3
import
openpyxl
from
openpyxl.chart
import
BarChart, Reference
wb
=
openpyxl.Workbook()
sheet
=
wb.active
for
i
in
range
(
10
):
sheet.append([i])
values
=
Reference(sheet, min_col
=
1
, min_row
=
1
,
max_col
=
1
, max_row
=
10
)
chart
=
BarChart()
chart.add_data(values)
chart.title
=
" BAR-CHART "
chart.x_axis.title
=
" X_AXIS "
chart.y_axis.title
=
" Y_AXIS "
sheet.add_chart(chart,
"E2"
)
wb.save(
"sample.xlsx"
)
Output:
Example 2:
Python3
import
openpyxl
from
openpyxl.chart
import
LineChart, Reference
wb
=
openpyxl.Workbook()
sheet
=
wb.active
for
i
in
range
(
10
):
sheet.append([i])
values
=
Reference(sheet, min_col
=
1
, min_row
=
1
,
max_col
=
1
, max_row
=
10
)
chart
=
LineChart()
chart.add_data(values)
chart.title
=
" LINE-CHART "
chart.x_axis.title
=
" X-AXIS "
chart.y_axis.title
=
" Y-AXIS "
sheet.add_chart(chart,
"E2"
)
wb.save(
"sample.xlsx"
)
Output:
Refer to the below articles to get detailed information about plotting in excel using Python.
- Plotting charts in excel sheet using openpyxl module | Set 1
- Plotting charts in excel sheet using openpyxl module | Set 2
- Plotting charts in excel sheet using openpyxl module | Set 3
Adding Images
For the purpose of importing images inside our worksheet, we would be using openpyxl.drawing.image.Image. The method is a wrapper over PIL.Image method found in PIL (pillow) library. Due to which it is necessary for the PIL (pillow) library to be installed in order to use this method.
Image Used:
Example:
Python3
import
openpyxl
from
openpyxl.drawing.image
import
Image
wb
=
openpyxl.Workbook()
sheet
=
wb.active
sheet.append([
10
,
2010
,
"Geeks"
,
4
,
"life"
])
img
=
Image(
"geek.jpg"
)
sheet.add_image(img,
'A2'
)
wb.save(
'sample.xlsx'
)
Output:
Refer to the below article to get detailed information about adding images.
- Openpyxl – Adding Image
Some More Functionality of Excel using Python
- How to delete one or more rows in excel using Openpyxl?
- Trigonometric operations in excel file using openpyxl
- How to copy data from one excel sheet to another
- How to Automate an Excel Sheet in Python?
What is the best way to read Excel (XLS) files with Python (not CSV files).
Is there a built-in package which is supported by default in Python to do this task?
asked May 31, 2010 at 10:28
1
I highly recommend xlrd for reading .xls
files. But there are some limitations(refer to xlrd github page):
Warning
This library will no longer read anything other than .xls files. For
alternatives that read newer file formats, please see
http://www.python-excel.org/.The following are also not supported but will safely and reliably be
ignored:- Charts, Macros, Pictures, any other embedded object, including embedded worksheets. - VBA modules - Formulas, but results of formula calculations are extracted. - Comments - Hyperlinks - Autofilters, advanced filters, pivot tables, conditional formatting, data validation
Password-protected files are not supported and cannot be read by this
library.
voyager mentioned the use of COM automation. Having done this myself a few years ago, be warned that doing this is a real PITA. The number of caveats is huge and the documentation is lacking and annoying. I ran into many weird bugs and gotchas, some of which took many hours to figure out.
UPDATE:
For newer .xlsx
files, the recommended library for reading and writing appears to be openpyxl (thanks, Ikar Pohorský).
Saikat
13.4k20 gold badges104 silver badges121 bronze badges
answered May 31, 2010 at 12:24
taleinattaleinat
8,3811 gold badge30 silver badges44 bronze badges
2
You can use pandas to do this, first install the required libraries:
$ pip install pandas openpyxl
See code below:
import pandas as pd
xls = pd.ExcelFile(r"yourfilename.xls") # use r before absolute file path
sheetX = xls.parse(2) #2 is the sheet number+1 thus if the file has only 1 sheet write 0 in paranthesis
var1 = sheetX['ColumnName']
print(var1[1]) #1 is the row number...
Skully
2,2723 gold badges22 silver badges31 bronze badges
answered May 23, 2017 at 4:04
3
You can choose any one of them http://www.python-excel.org/
I would recommended python xlrd library.
install it using
pip install xlrd
import using
import xlrd
to open a workbook
workbook = xlrd.open_workbook('your_file_name.xlsx')
open sheet by name
worksheet = workbook.sheet_by_name('Name of the Sheet')
open sheet by index
worksheet = workbook.sheet_by_index(0)
read cell value
worksheet.cell(0, 0).value
answered Apr 6, 2017 at 14:15
SomilSomil
1,9031 gold badge20 silver badges35 bronze badges
1
I think Pandas is the best way to go. There is already one answer here with Pandas using ExcelFile
function, but it did not work properly for me. From here I found the read_excel
function which works just fine:
import pandas as pd
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
print(dfs.head(10))
P.S. You need to have the xlrd
installed for read_excel
function to work
Update 21-03-2020: As you may see here, there are issues with the xlrd
engine and it is going to be deprecated. The openpyxl
is the best replacement. So as described here, the canonical syntax should be:
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name", engine="openpyxl")
Update 03-03-2023: There are now several other options available. For example the Polars library that is written in Rust:
import polars as pl
dfs = pl.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
Feel free to also check the PyArrow and pyodbc libraries.
answered Jun 12, 2018 at 10:35
Foad S. FarimaniFoad S. Farimani
12k15 gold badges72 silver badges181 bronze badges
3
For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.
def xlsx(fname):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
if el.tag.endswith('}v'): # Example: <v>84</v>
value = el.text
if el.tag.endswith('}c'): # Example: <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
letter = el.attrib['r'] # Example: AZ22
while letter[-1].isdigit():
letter = letter[:-1]
row[letter] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.
def xlsx(fname,sheet):
import zipfile
from xml.etree.ElementTree import iterparse
import re
z = zipfile.ZipFile(fname)
if 'xl/sharedStrings.xml' in z.namelist():
# Get shared strings
strings = [element.text for event, element
in iterparse(z.open('xl/sharedStrings.xml'))
if element.tag.endswith('}t')]
sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
if element.tag.endswith('}sheet') }
rows = []
row = {}
value = ''
if sheet in sheets:
sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
#print(sheet,sheetfile)
for event, element in iterparse(z.open(sheetfile)):
# get value or index to shared strings
if element.tag.endswith('}v') or element.tag.endswith('}t'):
value = element.text
# If value is a shared string, use value as an index
if element.tag.endswith('}c'):
if element.attrib.get('t') == 's':
value = strings[int(value)]
# split the row/col information so that the row leter(s) can be separate
letter = re.sub('d','',element.attrib['r'])
row[letter] = value
value = ''
if element.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
answered Oct 28, 2018 at 11:53
2
If you need old XLS format. Below code for ansii ‘cp1251’.
import xlrd
file=u'C:/Landau/task/6200.xlsx'
try:
book = xlrd.open_workbook(file,encoding_override="cp1251")
except:
book = xlrd.open_workbook(file)
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
for rx in range(sh.nrows):
print(sh.row(rx))
answered Nov 17, 2019 at 5:15
1
For older .xls
files, you can use xlrd
either you can use xlrd
directly by importing it. Like below
import xlrd
wb = xlrd.open_workbook(file_name)
Or you can also use pandas pd.read_excel()
method, but do not forget to specify the engine, though the default is xlrd
, it has to be specified.
pd.read_excel(file_name, engine = xlrd)
Both of them work for older .xls
file formats.
Infact I came across this when I used OpenPyXL
, i got the below error
InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.
answered Aug 12, 2020 at 6:06
2
You can use any of the libraries listed here (like Pyxlreader that is based on JExcelApi, or xlwt), plus COM automation to use Excel itself for the reading of the files, but for that you are introducing Office as a dependency of your software, which might not be always an option.
answered May 31, 2010 at 10:46
Esteban KüberEsteban Küber
36.1k15 gold badges83 silver badges97 bronze badges
1
You might also consider running the (non-python) program xls2csv. Feed it an xls file, and you should get back a csv.
answered Nov 25, 2012 at 21:43
2
with open(csv_filename) as file:
data = file.read()
with open(xl_file_name, 'w') as file:
file.write(data)
You can turn CSV to excel like above with inbuilt packages. CSV can be handled with an inbuilt package of dictreader and dictwriter which will work the same way as python dictionary works. which makes it a ton easy
I am currently unaware of any inbuilt packages for excel but I had come across openpyxl. It was also pretty straight forward and simple You can see the code snippet below hope this helps
import openpyxl
book = openpyxl.load_workbook(filename)
sheet = book.active
result =sheet['AP2']
print(result.value)
answered Jun 19, 2020 at 12:26
For older Excel files there is the OleFileIO_PL module that can read the OLE structured storage format used.
answered Sep 18, 2013 at 20:35
Gavin SmithGavin Smith
3,0661 gold badge18 silver badges24 bronze badges
If the file is really an old .xls, this works for me on python3 just using base open() and pandas:
df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='t')
Note that the file I’m using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.
I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.
answered Dec 14, 2020 at 21:16
1