Питон создание файла excel

В этом уроке я расскажу, как создать файл excel в Python с помощью библиотеки openpyxl.

Многие приложения, работающие с данными, нуждаются в экспорте этих данных в различные форматы. Очень распространенным и широко используемым форматом являются электронные таблицы.

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

Содержание

  • 1 Установка openpyxl
  • 2 Создание файла excel в python
  • 3 Создание листа
  • 4 Доступ к листу
  • 5 Доступ к ячейке
  • 6 Запись значений в ячейку
  • 7 Сохранение списка значений
  • 8 Сохранение книги excel в Python
    • 8.1 Похожие записи

Поскольку это внешняя библиотека, первое, что вы должны сделать для использования openpyxl, это установить ее.

Создайте новый каталог для вашего проекта, получите к нему доступ и запустите виртуальную среду.

После активации виртуальной среды выполните следующую команду из терминала для установки openpyxl:

$> pip install openpyxl

Создание файла excel в python

Как вы, возможно, знаете электронные таблицы группируются в книги. Книга – это родительская сущность электронной таблицы (обычно соответствующая файлу excel). В свою очередь, она состоит из одного или нескольких листов.

Книга Excel состоит как минимум из одного листа. Лист, с которым вы работаете, называется активным листом.

Для начала работы с openpyxl вам не нужно сохранять какой-либо файл в файловой системе. Вы просто создаете книгу.

В приведенном ниже коде вы узнаете, как создать книгу в openpyxl:

import openpyxl wb = openpyxl.Workbook()

Code language: JavaScript (javascript)

Переменная wb является экземпляром пустой книги. Вновь созданная книга содержит один лист, который является активным. Доступ к нему можно получить через активный атрибут.

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

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

>>> import openpyxl >>> wb = openpyxl.Workbook() >>> hoja = wb.active >>> print(f'Active list: {list.title}') Active list: Sheet >>> list.title = "Values" >>> print(f'Active list: {wb.active.title}') Active list: Values

Code language: PHP (php)

Создание листа

Помимо листа по умолчанию, с помощью openpyxl можно создать несколько листов в книге, используя метод create_sheet() у workbook как показано ниже (продолжение предыдущего примера):

# Добавление листа 'Sheet' в конец (по умолчанию). >>> list1 = wb.create_sheet("List") # Добавим лист 'Sheet' в первую позицию. # Если "List" существует, добавим цифру 1 в конец имени >>> list2 = wb.create_sheet("List", 0) # Добавим лист "Another list" на позицию 1 >>> wb.create_sheet(index=1, title="Another list") # Вывод на экран названий листов >>> print(wb.sheetnames) ['List1', 'Another list', 'Values', 'List']

Code language: PHP (php)

Также можно создать копию листа с помощью метода copy_worksheet():

>>> sourse = wb.active >>> new = wb.copy_worksheet(sourse)

Code language: JavaScript (javascript)

Доступ к листу

Как я уже говорил в предыдущем разделе, имена листов являются очень важным свойством, поскольку они позволяют нам обращаться к ним напрямую, рассматривая workbook как словарь. Продолжаем пример:

>>> list = wb.active # Это лист, который находится в индексе 0 >>> print(f'Active list: {list.title}') Active list: list1 >>> list = wb['Another list'] >>> wb.active = list >>> print(f'Active list: {wb.active.title}') Active list: Another list

Code language: PHP (php)

С другой стороны, как мы видели в предыдущем разделе, можно получить список с именами всех листов, обратившись к свойству sheetnames у workbook. Также можно перебирать все листы:

>>> print(wb.sheetnames) ['List1', 'Another list', 'Values', 'List'] >>> for list in wb: ... print(list.title) List1 Another list Values List

Code language: PHP (php)

Доступ к ячейке

До сих пор мы видели, как создать книгу, листы и как получить к ним доступ. Теперь перейдем к самому главному – как получить доступ к значению ячейки и как сохранить данные.

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

Вот как получить доступ к ячейке в столбце A и строке 1:

>>> wb = openpyxl.Workbook() >>> hoja = wb.active >>> a1 = list["A1"] >>> print(a1.value) None

Code language: PHP (php)

Также можно получить доступ к ячейке, используя обозначения строк и столбцов, с помощью метода cell() следующим образом:

>>> b2 = list.cell(row=2, column=2) >>> print(b2.value)

Code language: PHP (php)

ВАЖНО: Когда создается книга, она не содержит ячеек. Ячейки создаются в памяти по мере обращения к ним, даже если они не содержат никакого значения.

Запись значений в ячейку

В предыдущем разделе вы могли заметить, что при выводе содержимого ячейки (print(a1.value)) всегда возвращалось None. Это происходит потому, что ячейка не содержит никакого значения.

Чтобы присвоить значение определенной ячейке, вы можете сделать это тремя различными способами:

# 1.- Присвоение значения непосредственно ячейке >>> list["A1"] = 10 >>> a1 = list["A1"] >>> print(a1.value) 10 # 2.- Использование обозначения строки, столбца со значением аргумента >>> b1 = list.cell(row=1, column=2, value=20) >>> print(b1.value) 20 # 3.- Обновление свойства значения ячейки >>> c1 = list.cell(row=1, column=3) >>> c1.value = 30 >>> print(c1.value) 30

Code language: PHP (php)

Сохранение списка значений

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

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

products = [ ('product_1', 'a859', 1500, 9.95), ('product_2', 'b125', 600, 4.95), ('product_3', 'c764', 200, 19.95), ('product_4', 'd399', 2000, 49.95) ]

Code language: JavaScript (javascript)

Как мы можем экспортировать эти данные в excel с помощью openpyxl? Самый простой способ – использовать метод append() объекта листа.

Вот как это можно сделать:

products = [ ('product_1', 'a859', 1500, 9.95), ('product_2', 'b125', 600, 4.95), ('product_3', 'c764', 200, 19.95), ('product_4', 'd399', 2000, 49.95) ] wb = openpyxl.Workbook() list = wb.active # Создание строки с заголовками list.append(('Название', 'Артикул', 'Количество', 'Цена')) for product in products: # продукт - кортеж со значениями продукта list.append(product)

Code language: PHP (php)

Сохранение книги excel в Python

В завершение этогй статьи я покажу вам, как сохранить файл excel в Python с помощью openpyxl.

Чтобы сохранить файл excel с помощью openpyxl, достаточно вызвать метод save() у workbook с именем файла. Это позволит сохранить рабочую книгу со всеми листами и данными в каждом из них.

Если мы сделаем это на предыдущем примере , то получим следующий результат:

wb.save('products.xlsx')

Code language: JavaScript (javascript)

Installation¶

Install openpyxl using pip. It is advisable to do this in a Python virtualenv
without system packages:

Note

There is support for the popular lxml library which will be used if it
is installed. This is particular useful when creating large files.

Warning

To be able to include images (jpeg, png, bmp,…) into an openpyxl file,
you will also need the “pillow” library that can be installed with:

or browse https://pypi.python.org/pypi/Pillow/, pick the latest version
and head to the bottom of the page for Windows binaries.

Working with a checkout¶

Sometimes you might want to work with the checkout of a particular version.
This may be the case if bugs have been fixed but a release has not yet been
made.

$ pip install -e hg+https://foss.heptapod.net/openpyxl/openpyxl/@3.1#egg=openpyxl

Create a workbook¶

There is no need to create a file on the filesystem to get started with openpyxl.
Just import the Workbook class and start work:

>>> from openpyxl import Workbook
>>> wb = Workbook()

A workbook is always created with at least one worksheet. You can get it by
using the Workbook.active property:

Note

This is set to 0 by default. Unless you modify its value, you will always
get the first worksheet by using this method.

You can create new worksheets using the Workbook.create_sheet() method:

>>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
# or
>>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
# or
>>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position

Sheets are given a name automatically when they are created.
They are numbered in sequence (Sheet, Sheet1, Sheet2, …).
You can change this name at any time with the Worksheet.title property:

Once you gave a worksheet a name, you can get it as a key of the workbook:

>>> ws3 = wb["New Title"]

You can review the names of all worksheets of the workbook with the
Workbook.sheetname attribute

>>> print(wb.sheetnames)
['Sheet2', 'New Title', 'Sheet1']

You can loop through worksheets

>>> for sheet in wb:
...     print(sheet.title)

You can create copies of worksheets within a single workbook:

Workbook.copy_worksheet() method:

>>> source = wb.active
>>> target = wb.copy_worksheet(source)

Note

Only cells (including values, styles, hyperlinks and comments) and
certain worksheet attributes (including dimensions, format and
properties) are copied. All other workbook / worksheet attributes
are not copied — e.g. Images, Charts.

You also cannot copy worksheets between workbooks. You cannot copy
a worksheet if the workbook is open in read-only or write-only
mode.

Playing with data¶

Accessing one cell¶

Now we know how to get a worksheet, we can start modifying cells content.
Cells can be accessed directly as keys of the worksheet:

This will return the cell at A4, or create one if it does not exist yet.
Values can be directly assigned:

There is also the Worksheet.cell() method.

This provides access to cells using row and column notation:

>>> d = ws.cell(row=4, column=2, value=10)

Note

When a worksheet is created in memory, it contains no cells. They are
created when first accessed.

Warning

Because of this feature, scrolling through cells instead of accessing them
directly will create them all in memory, even if you don’t assign them a value.

Something like

>>> for x in range(1,101):
...        for y in range(1,101):
...            ws.cell(row=x, column=y)

will create 100×100 cells in memory, for nothing.

Accessing many cells¶

Ranges of cells can be accessed using slicing:

>>> cell_range = ws['A1':'C2']

Ranges of rows or columns can be obtained similarly:

>>> colC = ws['C']
>>> col_range = ws['C:D']
>>> row10 = ws[10]
>>> row_range = ws[5:10]

You can also use the Worksheet.iter_rows() method:

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
...    for cell in row:
...        print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>

Likewise the Worksheet.iter_cols() method will return columns:

>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
...     for cell in col:
...         print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.A2>
<Cell Sheet1.B1>
<Cell Sheet1.B2>
<Cell Sheet1.C1>
<Cell Sheet1.C2>

Note

For performance reasons the Worksheet.iter_cols() method is not available in read-only mode.

If you need to iterate through all the rows or columns of a file, you can instead use the
Worksheet.rows property:

>>> ws = wb.active
>>> ws['C9'] = 'hello world'
>>> tuple(ws.rows)
((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
(<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
(<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
(<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>),
(<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>),
(<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>),
(<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
(<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
(<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))

or the Worksheet.columns property:

>>> tuple(ws.columns)
((<Cell Sheet.A1>,
<Cell Sheet.A2>,
<Cell Sheet.A3>,
<Cell Sheet.A4>,
<Cell Sheet.A5>,
<Cell Sheet.A6>,
...
<Cell Sheet.B7>,
<Cell Sheet.B8>,
<Cell Sheet.B9>),
(<Cell Sheet.C1>,
<Cell Sheet.C2>,
<Cell Sheet.C3>,
<Cell Sheet.C4>,
<Cell Sheet.C5>,
<Cell Sheet.C6>,
<Cell Sheet.C7>,
<Cell Sheet.C8>,
<Cell Sheet.C9>))

Note

For performance reasons the Worksheet.columns property is not available in read-only mode.

Values only¶

If you just want the values from a worksheet you can use the Worksheet.values property.
This iterates over all the rows in a worksheet but returns just the cell values:

for row in ws.values:
   for value in row:
     print(value)

Both Worksheet.iter_rows() and Worksheet.iter_cols() can
take the values_only parameter to return just the cell’s value:

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
...   print(row)

(None, None, None)
(None, None, None)

Data storage¶

Once we have a Cell, we can assign it a value:

>>> c.value = 'hello, world'
>>> print(c.value)
'hello, world'

>>> d.value = 3.14
>>> print(d.value)
3.14

Saving to a file¶

The simplest and safest way to save a workbook is by using the
Workbook.save() method of the Workbook object:

>>> wb = Workbook()
>>> wb.save('balances.xlsx')

Warning

This operation will overwrite existing files without warning.

Note

The filename extension is not forced to be xlsx or xlsm, although you might have
some trouble opening it directly with another application if you don’t
use an official extension.

As OOXML files are basically ZIP files, you can also open it with your
favourite ZIP archive manager.

If required, you can specify the attribute wb.template=True, to save a workbook
as a template:

>>> wb = load_workbook('document.xlsx')
>>> wb.template = True
>>> wb.save('document_template.xltx')

Saving as a stream¶

If you want to save the file to a stream, e.g. when using a web application
such as Pyramid, Flask or Django then you can simply provide a
NamedTemporaryFile():

>>> from tempfile import NamedTemporaryFile
>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> with NamedTemporaryFile() as tmp:
        wb.save(tmp.name)
        tmp.seek(0)
        stream = tmp.read()

Warning

You should monitor the data attributes and document extensions
for saving documents in the document templates and vice versa,
otherwise the result table engine can not open the document.

Note

The following will fail:

>>> wb = load_workbook('document.xlsx')
>>> # Need to save with the extension *.xlsx
>>> wb.save('new_document.xlsm')
>>> # MS Excel can't open the document
>>>
>>> # or
>>>
>>> # Need specify attribute keep_vba=True
>>> wb = load_workbook('document.xlsm')
>>> wb.save('new_document.xlsm')
>>> # MS Excel will not open the document
>>>
>>> # or
>>>
>>> wb = load_workbook('document.xltm', keep_vba=True)
>>> # If we need a template document, then we must specify extension as *.xltm.
>>> wb.save('new_document.xlsm')
>>> # MS Excel will not open the document

Loading from a file¶

You can use the openpyxl.load_workbook() to open an existing workbook:

>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = 'empty_book.xlsx')
>>> sheet_ranges = wb['range names']
>>> print(sheet_ranges['D18'].value)
3

Note

There are several flags that can be used in load_workbook.

  • data_only controls whether cells with formulae have either the

formula (default) or the value stored the last time Excel read the sheet.

  • keep_vba controls whether any Visual Basic elements are preserved or

not (default). If they are preserved they are still not editable.

  • read-only opens workbooks in a read-only mode. This uses much less

memory and is faster but not all features are available (charts, images,
etc.)

  • rich_text controls whether any rich-text formatting in cells is

preserved. The default is False.

  • keep_links controls whether data cached from external workbooks is

preserved.

Warning

openpyxl does currently not read all possible items in an Excel file so
shapes will be lost from existing files if they are opened and saved with
the same name.

Errors loading workbooks¶

Sometimes openpyxl will fail to open a workbook. This is usually because there is something wrong with the file.
If this is the case then openpyxl will try and provide some more information. Openpyxl follows the OOXML specification closely and will reject files that do not because they are invalid. When this happens you can use the exception from openpyxl to inform the developers of whichever application or library produced the file. As the OOXML specification is publicly available it is important that developers follow it.

You can find the spec by searching for ECMA-376, most of the implementation specifics are in Part 4.

This ends the tutorial for now, you can proceed to the Simple usage section

Электронные таблицы Excel — это интуитивно понятный и удобный способ манипулирования большими наборами данных без какой-либо предварительной технической подготовки. По этому, это один из форматов, с которым, в какой-то момент времени, вам придется иметь дело. Часто будут стоять задачи по извлечению каких-то данных из базы данных или файла логов в электронную таблицу Excel, или наоборот, преобразовывать электронную таблицу Excel в какую-либо более удобную программную форму, примеров этому масса.

Модуль openpyxl — это библиотека Python для чтения/записи форматов Office Open XML (файлов Excel 2010) с расширениями xlsx/xlsm/xltx/xltm.

Установка модуля openpyxl в виртуальное окружение.

Модуль openpyxl размещен на PyPI, поэтому установка относительно проста.

# создаем виртуальное окружение, если нет
$ python3 -m venv .venv --prompt VirtualEnv
# активируем виртуальное окружение 
$ source .venv/bin/activate
# ставим модуль openpyxl
(VirtualEnv):~$ python3 -m pip install -U openpyxl

Основы работы с файлами Microsoft Excel на Python.

  • Создание книги Excel.
    • Новый рабочий лист книги Excel.
    • Копирование рабочего листа книги Excel.
    • Удаление рабочего листа книги Excel.
  • Доступ к ячейке электронной таблицы и ее значению.
  • Доступ к диапазону ячеек листа электронной таблицы.
  • Получение только значений ячеек листа.
  • Добавление данных в ячейки списком.
  • Сохранение созданной книги в файл Excel.
    • Сохранение данных книги в виде потока.
  • Загрузка документа XLSX из файла.

Создание книги Excel.

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

>>> from openpyxl import Workbook
# создаем книгу 
>>> wb = Workbook()
# делаем единственный лист активным 
>>> ws = wb.active

Новый рабочий лист книги Excel.

Новые рабочие листы можно создавать, используя метод Workbook.create_sheet():

# вставить рабочий лист в конец (по умолчанию)
>>> ws1 = wb.create_sheet("Mysheet")
# вставить рабочий лист в первую позицию
>>> ws2 = wb.create_sheet("Mysheet", 0)
# вставить рабочий лист в предпоследнюю позицию
>>> ws3 = wb.create_sheet("Mysheet", -1)

Листам автоматически присваивается имя при создании. Они нумеруются последовательно (Sheet, Sheet1, Sheet2, …). Эти имена можно изменить в любое время с помощью свойства Worksheet.title:

Цвет фона вкладки с этим заголовком по умолчанию белый. Можно изменить этот цвет, указав цветовой код RRGGBB для атрибута листа Worksheet.sheet_properties.tabColor:

>>> ws.sheet_properties.tabColor = "1072BA"

Рабочий лист можно получить, используя его имя в качестве ключа экземпляра созданной книги Excel:

Что бы просмотреть имена всех рабочих листов книги, необходимо использовать атрибут Workbook.sheetname. Также можно итерироваться по рабочим листам книги Excel.

>>> wb.sheetnames
# ['Mysheet1', 'NewPage', 'Mysheet2', 'Mysheet']

>>> for sheet in wb:
...     print(sheet.title)
# Mysheet1
# NewPage
# Mysheet2
# Mysheet

Копирование рабочего листа книги Excel.

Для создания копии рабочих листов в одной книге, необходимо воспользоваться методом Workbook.copy_worksheet():

>>> source_page = wb.active
>>> target_page = wb.copy_worksheet(source_page)

Примечание. Копируются только ячейки (значения, стили, гиперссылки и комментарии) и определенные атрибуты рабочего листа (размеры, формат и свойства). Все остальные атрибуты книги/листа не копируются, например, изображения или диаграммы.

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

Удаление рабочего листа книги Excel.

Очевидно, что встает необходимость удалить лист электронной таблицы, который уже существует. Модуль openpyxl дает возможность удалить лист по его имени. Следовательно, сначала необходимо выяснить, какие листы присутствуют в книге, а потом удалить ненужный. За удаление листов книги отвечает метод Workbook.remove().

Смотрим пример:

# выясним, названия листов присутствуют в книге
>>> name_list = wb.sheetnames
>>> name_list
# ['Mysheet1', 'NewPage', 'Mysheet2', 'Mysheet', 'Mysheet1 Copy']

# допустим, что нам не нужны первый и последний
# удаляем первый лист по его имени с проверкой 
# существования такого имени в книге
>>> if 'Mysheet1' in wb.sheetnames:
        # Если лист с именем `Mysheet1` присутствует
        # в списке листов экземпляра книги, то удаляем
...     wb.remove(wb['Mysheet1'])
...
>>> wb.sheetnames
# ['NewPage', 'Mysheet2', 'Mysheet', 'Mysheet1 Copy']

# удаляем последний лист через оператор
#  `del`, имя листа извлечем по индексу 
# полученного списка `name_list`
>>> del wb[name_list[-1]]
>>> wb.sheetnames
# ['NewPage', 'Mysheet2', 'Mysheet']

Доступ к ячейке и ее значению.

После того как выбран рабочий лист, можно начинать изменять содержимое ячеек. К ячейкам можно обращаться непосредственно как к ключам рабочего листа, например ws['A4']. Это вернет ячейку на A4 или создаст ее, если она еще не существует. Значения могут быть присвоены напрямую:

>>> ws['A4'] = 5
>>> ws['A4']
# <Cell 'NewPage'.A4>
>>> ws['A4'].value
# 5
>>> ws['A4'].column
# 1
>>> ws['A4'].row
# 4

Если объект ячейки присвоить переменной, то этой переменной, также можно присваивать значение:

>>> c = ws['A4']
>>> c.value = c.value * 2
>>> c.value
# 10

Существует также метод Worksheet.cell(). Он обеспечивает доступ к ячейкам с непосредственным указанием значений строк и столбцов:

>>> d = ws.cell(row=4, column=2, value=10)
>>> d
# <Cell 'NewPage'.B4>
>>> d.value = 3.14
>>> print(d.value)
# 3.14

Примечание. При создании рабочего листа в памяти, он не содержит ячеек. Ячейки создаются при первом доступе к ним.

Важно! Из-за такого поведения, простой перебор ячеек в цикле, создаст объекты этих ячеек в памяти, даже если не присваивать им значения.

Не запускайте этот пример, поверьте на слово:

# создаст в памяти 100x100=10000 пустых объектов  
# ячеек, просто так израсходовав оперативную память.
>>> for x in range(1,101):
...        for y in range(1,101):
...            ws.cell(row=x, column=y)

Доступ к диапазону ячеек листа электронной таблицы.

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

>>> cell_range = ws['A1':'C2']
>>> cell_range
# ((<Cell 'NewPage'.A1>, <Cell 'NewPage'.B1>, <Cell 'NewPage'.C1>), 
# (<Cell 'NewPage'.A2>, <Cell 'NewPage'.B2>, <Cell 'NewPage'.C2>))

Аналогично можно получить диапазоны имеющихся строк или столбцов на листе:

# Все доступные ячейки в колонке `C`
>>> colC = ws['C']
# Все доступные ячейки в диапазоне колонок `C:D`
>>> col_range = ws['C:D']
# Все доступные ячейки в строке 10
>>> row10 = ws[10]
# Все доступные ячейки в диапазоне строк `5:10`
>>> row_range = ws[5:10]

Можно также использовать метод Worksheet.iter_rows():

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
...    for cell in row:
...        print(cell)
# <Cell Sheet1.A1>
# <Cell Sheet1.B1>
# <Cell Sheet1.C1>
# <Cell Sheet1.A2>
# <Cell Sheet1.B2>
# <Cell Sheet1.C2>

Точно так же метод Worksheet.iter_cols() будет возвращать столбцы:

>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
...     for cell in col:
...         print(cell)
# <Cell Sheet1.A1>
# <Cell Sheet1.A2>
# <Cell Sheet1.B1>
# <Cell Sheet1.B2>
# <Cell Sheet1.C1>
# <Cell Sheet1.C2>

Примечание. Из соображений производительности метод Worksheet.iter_cols() недоступен в режиме только для чтения.

Если необходимо перебрать все строки или столбцы файла, то можно использовать свойство Worksheet.rows:

>>> ws = wb.active
>>> ws['C9'] = 'hello world'
>>> tuple(ws.rows)
# ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
# (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
# (<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
# ...
# (<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
# (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
# (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))

или свойство Worksheet.columns:

>>> tuple(ws.columns)
# ((<Cell Sheet.A1>,
# <Cell Sheet.A2>,
# ...
# <Cell Sheet.B8>,
# <Cell Sheet.B9>),
# (<Cell Sheet.C1>,
# <Cell Sheet.C2>,
# ...
# <Cell Sheet.C8>,
# <Cell Sheet.C9>))

Примечание. Из соображений производительности свойство Worksheet.columns недоступно в режиме только для чтения.

Получение только значений ячеек активного листа.

Если просто нужны значения из рабочего листа, то можно использовать свойство активного листа Worksheet.values. Это свойство перебирает все строки на листе, но возвращает только значения ячеек:

for row in ws.values:
   for value in row:
     print(value)

Для возврата только значения ячейки, методы Worksheet.iter_rows() и Worksheet.iter_cols(), представленные выше, могут принимать аргумент values_only:

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
...   print(row)
# (None, None, None)
# (None, None, None)

Добавление данных в ячейки листа списком.

Модуль openpyxl дает возможность супер просто и удобно добавлять данные в конец листа электронной таблицы. Такое удобство обеспечивается методом объекта листа Worksheet.append(iterable), где аргумент iterable — это любой итерируемый объект (список, кортеж и т.д.). Такое поведение позволяет, без костылей, переносить в электронную таблицу данные из других источников, например CSV файлы, таблицы баз данных, дата-фреймы из Pandas и т.д.

Метод Worksheet.append() добавляет группу значений в последнюю строку, которая не содержит данных.

  • Если это список: все значения добавляются по порядку, начиная с первого столбца.
  • Если это словарь: значения присваиваются столбцам, обозначенным ключами (цифрами или буквами).

Варианты использования:

  • добавление списка: .append([‘ячейка A1’, ‘ячейка B1’, ‘ячейка C1’])
  • добавление словаря:
    • вариант 1: .append({‘A’ : ‘ячейка A1’, ‘C’ : ‘ячейка C1’}), в качестве ключей используются буквы столбцов.
    • вариант 2: .append({1 : ‘ячейка A1’, 3 : ‘ячейка C1’}), в качестве ключей используются цифры столбцов.

Пример добавление данных из списка:

# существующие листы рабочей книги
>>> wb.sheetnames
# ['NewPage', 'Mysheet2', 'Mysheet']

# добавим данные в лист с именем `Mysheet2`
>>> ws = wb["Mysheet2"]
# создадим произвольные данные, используя
# вложенный генератор списков
>>> data = [[row*col for col in range(1, 10)] for row in range(1, 31)]
>>> data
# [
#     [1, 2, 3, 4, 5, 6, 7, 8, 9], 
#     [2, 4, 6, 8, 10, 12, 14, 16, 18], 
# ...
# ...
#     [30, 60, 90, 120, 150, 180, 210, 240, 270]
# ]

# добавляем данные в выбранный лист
>>> for row in data:
...     ws.append(row)
...

Вот и все, данные добавлены… Просто? Не просто, а супер просто!

Сохранение созданной книги в файл Excel.

Самый простой и безопасный способ сохранить книгу, это использовать метод Workbook.save() объекта Workbook:

>>> wb = Workbook()
>>> wb.save('test.xlsx')

Внимание. Эта операция перезапишет существующий файл без предупреждения!!!

После сохранения, можно открыть полученный файл в Excel и посмотреть данные, выбрав лист с именем NewPage.

Примечание. Расширение имени файла не обязательно должно быть xlsx или xlsm, хотя могут возникнуть проблемы с его открытием непосредственно в другом приложении. Поскольку файлы OOXML в основном представляют собой ZIP-файлы, их также можете открыть с помощью своего любимого менеджера ZIP-архивов.

Сохранение данных книги в виде потока.

Если необходимо сохранить файл в поток, например, при использовании веб-приложения, такого как Flask или Django, то можно просто предоставить tempfile.NamedTemporaryFile():

from tempfile import NamedTemporaryFile
from openpyxl import Workbook

wb = Workbook()

with NamedTemporaryFile() as tmp:
    wb.save(tmp.name)
    tmp.seek(0)
    stream = tmp.read()

Можно указать атрибут template=True, чтобы сохранить книгу как шаблон:

>>> from openpyxl import load_workbook
>>> wb = load_workbook('test.xlsx')
>>> wb.template = True
>>> wb.save('test_template.xltx')

Примечание. Атрибут wb.template по умолчанию имеет значение False, это означает — сохранить как документ.

Внимание. Следующее не удастся:

>>> from openpyxl import load_workbook
>>> wb = load_workbook('test.xlsx')
# Необходимо сохранить с расширением *.xlsx
>>> wb.save('new_test.xlsm') # MS Excel не может открыть документ

# Нужно указать атрибут `keep_vba=True`
>>> wb = load_workbook('test.xlsm')
>>> wb.save('new_test.xlsm')

>>> wb = load_workbook('test.xltm', keep_vba=True)
# Если нужен шаблон документа, то необходимо указать расширение *.xltm.
>>> wb.save('new_test.xlsm') # MS Excel не может открыть документ

Загрузка документа XLSX из файла.

Чтобы открыть существующую книгу Excel необходимо использовать функцию openpyxl.load_workbook():

>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
>>> print(wb2.sheetnames)
# ['Mysheet1', 'NewPage', 'Mysheet2', 'Mysheet']

Есть несколько флагов, которые можно использовать в функции openpyxl.load_workbook().

  • data_only: определяет, будут ли содержать ячейки с формулами — формулу (по умолчанию) или только значение, сохраненное/посчитанное при последнем чтении листа Excel.
  • keep_vba определяет, сохраняются ли какие-либо элементы Visual Basic (по умолчанию). Если они сохранены, то они не могут изменяться/редактироваться.

Working with Excel files in Python is not that much hard as you might think. In this tutorial, we are going to learn how to create, read and modify .xlsx files using python.

Introduction

Xlsx files are the most widely used documents in the technology field. Data Scientists uses spreadsheets more than anyone else in the world and obivously they don’t do it manually.

We will need a module called openpyxl which is used to read, create and work with .xlsx files in python. There are some other modules like xlsxwriter, xlrd, xlwt, etc., but, they don’t have methods for performing all the operations on excel files. To install the openpyxl module run the following command in command line:

pip install openpyxl

Let’s see what all operations one can perform using the openpyxl module after importing the module in our code, which is simple:

import openpyxl

Once we have imported the module in our code, all we have to do is use various methods of the module to rad, write and create .xlsx files.


Creating New .xlsx File

In this program, we are going to create a new .xlsx file.

import openpyxl

## CREATING XLSX FILE

## initializing the xlsx
xlsx = openpyxl.Workbook()

## creating an active sheet to enter data
sheet = xlsx.active

## entering data into the A1 and B1 cells in the sheet
sheet['A1'] = 'Studytonight'
sheet['B1'] = 'A Programming Site'

## saving the xlsx file using 'save' method
xlsx.save('sample.xlsx')

The above program creates an .xlsx file with the name sample.xlsx in the present working directory.

Creating Xlsx File using openpyxl python module


Writing to a Cell

There are to ways to write to a cell. The first method is the one which we used in the program above and the second method is using the cell() method by passing the row and column numbers.

Let’s see how the second way works:

import openpyxl

## initializing the xlsx
xlsx = openpyxl.Workbook()

## creating an active sheet to enter data
sheet = xlsx.active

## entering data into the cells using 1st method
sheet['A1'] = 'Studytonight'
sheet['B2'] = 'Cell B2'

## entering data into the cells using 2nd method
sheet.cell(row = 1, column = 2).value = 'A Programming Site'
sheet.cell(row = 2, column = 1).value = "B1"

## saving the xlsx file using 'save' method
xlsx.save('write_to_cell.xlsx')

adding cell data to Xlsx File using openpyxl python module

In the second method above, we are getting the cell with the row and column values. After getting the cell, we are assigning a value to it using the value variable.


Appending Data to a .xlsx file

The append() method is used to append the data to any cell. Here is an example:

import openpyxl

## initializing the xlsx
xlsx = openpyxl.Workbook()

## creating an active sheet to enter data
sheet = xlsx.active

## creating data to append
data = [
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9],
         [10, 11, 12]
       ]

## appending row by row to the sheet
for row in data:
    ## append method is used to append the data to a cell
    sheet.append(row)

## saving the xlsx file using 'save' method
xlsx.save('appending.xlsx')

Appending data to .xlsx file using openpyxl module python

Using the above program, we have appended 4 rows and 3 column values in our .xlsx file. You can also use tuples or any iteratable object instead of lists.


Reading Data from a Cell

We are now going to learn how to read data from a cell in a xlsx file. We will use the previously created .xlsx file to read data from the cell.

import openpyxl

## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('sample.xlsx')

## getting the sheet to active
sheet = xlsx.active

## getting the reference of the cells which we want to get the data from
name = sheet['A1']
tag = sheet.cell(row = 1, column = 2)

## printing the values of cells
print(name.value)
print(tag.value)

Output of above Program:

Studytonight
A Programming Site

Reading Data from Multiple Cells

Now we are going to use the appending.xlsx file to read data. It contains numeric values from 1 to 12 saved in the cells in form of 4 rows and 3 columns.

import openpyxl

## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')

## getting the sheet to active
sheet = xlsx.active

## getting the reference of the cells which we want to get the data from
values = sheet['A1' : 'C4']

## printing the values of cells
for c1, c2, c3 in values:
print("{} {} {}".format(c1.value, c2.value, c3.value))

Output of above Program:

1 2 3
4 5 6
7 8 9
10 11 12

Slicing method applied on cells returns a tuple containing each row as a tuple. And we can print all the cell’s data using a loop.


Getting Dimensions of an .xlsx Sheet

Getting the dimensions of an .xlsx sheet is also possible and super-easy using the dimensions method.

import openpyxl

## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')

## getting the sheet to active
sheet = xlsx.active

## getting the reference of the cells which we want to get the data from
dimensions = sheet.dimensions

## printing the dimensions of the sheet
print(dimensions)

Output of above Program:

A1:C4

The output of the dimensions method is the range of the sheet from which cell to which cell the data is present.


Getting Data from Rows of .xlsx File

We can also get data from all the rows of an xlsx file by using the rows method.

import openpyxl

## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')

## getting the sheet to active
sheet = xlsx.active

## getting the reference of the cells which we want to get the data from
rows = sheet.rows

## printing the values of cells using rows
for row in rows:
    for cell in row:
        print(cell.value, end = ' ')

    print("n")

Output of above Program:

1 2 3 
4 5 6 
7 8 9 
10 11 12

rows method returns a generator which contains all rows of the sheet.


Getting Data from Columns of .xlsx File

We can get data from all the columns of an xlsx file by using the columns method.

import openpyxl

## opening the previously created xlsx file using 'load_workbook()' method
xlsx = openpyxl.load_workbook('appending.xlsx')

## getting the sheet to active
sheet = xlsx.active

## getting the reference of the cells which we want to get the data from
columns = sheet.columns

## printing the values of cells using rows
for column in columns:
    for cell in column:
        print(cell.value, end = ' ')
    print("n")

Output of above Program:

1 4 7 10 
2 5 8 11 
3 6 9 12

columns method returns a generator which contains all the columns of the sheet.


Working with Excel Sheets

In this section we will see how we can create more sheets, get name of sheets and even change the name of any given sheet etc.

1. Changing the name of an Excel Sheet

We can also change the name of a given excel sheet using the title variable. Let’s see an example:

import openpyxl

## initializing the xlsx
xlsx = openpyxl.Workbook()

## creating an active sheet to enter data
sheet = xlsx.active

## entering data into the A1 and B1 cells in the sheet
sheet['A1'] = 'Studytonight'
sheet['B1'] = 'A Programming Site'

## setting the title for the sheet
sheet.title = "Sample"

## saving the xlsx file using 'save' method
xlsx.save('sample.xlsx')

change sheet name using openpyxl module in python


2. Getting Excel Sheet name

Getting the names of all the sheets present in xlsx file is super easy using the openpyxl module. We can use the method called get_sheet_names() to get names of all the sheets present in the excel file.

import openpyxl

## initializing the xlsx
xlsx = openpyxl.load_workbook('sample.xlsx')

## getting all sheet names
names = xlsx.get_sheet_names()

print(names)

Output of above Program:

['Sample']

3. Creating more than one Sheet in an Excel File

When creating our first xlsx file, we only created one sheet. Let’s see how to create multiple sheets and give names to them.

import openpyxl

## initializing the xlsx
xlsx = openpyxl.Workbook()

## creating sheets
xlsx.create_sheet("School")
xlsx.create_sheet("College")
xlsx.create_sheet("University")

## saving the xlsx file using 'save' method
xlsx.save('multiple_sheets.xlsx')

Multiple Sheets

As you can see in the snapshot above that a new excel file is created with 3 new sheets with different names provided by us in the program.


4. Adding Data to Multiple Sheets

Entering data into different sheets present in xlsx file can also be done easily. In the program below, we will get the sheets by their names individually or all at once as we have done above. Let’s see how to get sheets using their name and enter data into them.

We will use previously created xlsx file called multiple_sheets.xlsx to enter the data into sheets.

import openpyxl

## initializing the xlsx
xlsx = openpyxl.Workbook()

## creating sheets
xlsx.create_sheet("School")
xlsx.create_sheet("College")
xlsx.create_sheet("University")

## getting sheet by it's name
school = xlsx.get_sheet_by_name("School")
school['A1'] = 1

## getting sheet by it's name
college = xlsx.get_sheet_by_name("College")
college['A1'] = 2

## getting sheet by it's name
university = xlsx.get_sheet_by_name("University")
university['A1'] = 3

## saving the xlsx file using 'save' method
xlsx.save('multiple_sheets.xlsx')

Creating multiple sheets in excel file using openpyxl python module

We can’t modify the existing xlsx file using the openpyxl module but we can read data from it.


Conclusion

We have seen different methods which can be used while working with xlsx files using Python. If you want to explore more methods available in the openpyxl module, then you can try them using the dir() method to get information about all methods of openpyxl module.

You can also see other modules like xlsxwriter, xlrd, xlwt, etc., for more functionalities. If you have already used any of these modules, do share your experience with us through comments section.

You may also like:

  • Converting Xlsx file To CSV file using Python
  • How to copy elements from one list to another in Python
  • Calculate Time taken by a Program to Execute in Python
  • Dlib 68 points Face landmark Detection with OpenCV and Python

Last Updated on March 11, 2022 by

We can use the openpyxl library to create an Excel File in Python. This ability is an essential step for any Excel process automation. The best part – we don’t even need to have the Excel program installed.

Library

Open up a command prompt, and use pip install to download openpyxl library:

pip install openpyxl

Create Excel Workbook and Add Worksheets using Python

For this step, we are creating an Excel file in Python and don’t need to open the Excel program. The below code creates an Excel file in memory, then adds two sheets, namely “Sheet_one” and “Sheet_two”.

Note:

  1. When a Workbook is created, by default it contains at least one sheet. So this file will contain three (3) sheets in total.
  2. This Excel file doesn’t exist on the hard drive yet and it doesn’t have a name.
from openpyxl import Workbook

wb = Workbook()
wb.create_sheet("Sheet_one")
wb.create_sheet("Sheet_two")

wb.sheetnames
['Sheet', 'Sheet_one', 'Sheet_two']

We can change the sheet name any time by setting the ws.title attribute:

wb['Sheet'].title = 'Sheet_zero'

wb.sheetnames
['Sheet_zero', 'Sheet_one', 'Sheet_two']

Copy A Worksheet

To copy a worksheet, call the wb.copy_worksheet() method:

ws0 = wb['Sheet_zero']
wb.copy_worksheet(ws0)

wb.sheetnames
['Sheet_zero', 'Sheet_one', 'sheet_two', 'Sheet_zero Copy']

Note that openpyxl has limitations and can not copy everything on a sheet. For example, Images and Charts will not be copied.

Changing Sheet/tab Color

We can use the .sheet_properties.tabColor attribute to set tab colors. The value has to be a RGB hex value, and the easiest way to get those values is from the “Hex” box on Excel’s color palette.

wb['Sheet_zero'].sheet_properties.tabColor ='00FF00'
Excel color palette
Excel color palette

Write Some Data Into Excel

Check out this tutorial to learn how to access Sheets and Cells.

Let’s put some values into “Sheet_one”. As the below code shows, it’s easy to access a cell using the column-row notation.

ws1 = wb['Sheet_one']

ws1['B2'] = 'Fruits'
ws1['C2'] = 'Sales'

To enter values into Sheet programmatically, it’s easier to use the cell() method, which takes two arguments: row and column, both starting from an index of 1.

fruits = ['Apple','Peach','Cherry','Watermelon']
sales = [100,200,300,400]

row_start = 3  #start below the header row 2
col_start = 2  #starts from column B
for i in range(0,len(fruits)):
    ws1.cell(row_start+i, col_start).value = fruits[i]
    ws1.cell(row_start+i, col_start+1).value = sales[i]
Python write data to Excel
Python write data to Excel

Saving Excel File

Up to this point, the entire Excel file including everything we’ve done is still inside our computer’s memory. We need to save the file to our disk by calling the wb.save() method. If we don’t do this step, our Excel file will disappear after shutting down the Python environment.

wb.save('book_eg.xlsx')

This is how we can create an Excel file using Python. Check the below for more resources.

Additional Resoruces

How to Access Excel File In Python

How to Use Python to Read Excel Formula

Work with Excel Named Range in Python

Понравилась статья? Поделить с друзьями:
  • Питон как записать в файл excel
  • Питон выгрузка в excel
  • Питон вывод в excel
  • Питон for word in
  • Питанию класса в excel