Python openpyxl open excel file

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

Introduction

In this article I show how to work Excel with openpyxl.

Environment

Runtime environment is as below.

  • python 3.6
  • openpyxl 2.5.6

Install

Use openpyxl. The openpyxl official document says ..

openpyxl is a Python library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files.

However, openpyxl can also work with Mac Excel 2016 on my Macbook Pro.

Let’s install with pip command.

Create new Excel file

Import openpyxl

At first, import Workbook class from openpyxl

1from openpyxl import Workbook

Create Workbook

The Workbook is a Class for Excel file in openpyxl.

Creating Workbook instance works creating a new empty workbook with at least one worksheet.

1# Create a Workbook
2wb = Workbook()

Change the name of Worksheet

Now change the name of Worksheet to “Changed Sheet” .

1ws =  wb.active
2ws.title = "Changed Sheet"

The active property in Workbook instance returns the reference to the active worksheet.

Save file

Save a file as sample_book.xlsx with save function.

1wb.save(filename = 'sample_book.xlsx')

The saved xlsx file exists in the same folder as the program.

download_file

Now open the file and check that the file name has been changed correctly.

rename_sheet

Open a Excel file that already exists

It is easy to get Workbook instance using load_workbook function.

1from openpyxl import load_workbook
2wb = load_workbook('sample_book.xlsx')
3print(wb.sheetnames)

Conclusion

It is available to ..

  • Create Excel file creating Workbook instance
  • Save a Excel file with save function
  • Change name of default Worksheet with active property
  • Open Excel file with load_workbook function

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.
    For example, users might have to go through thousands of rows and pick out a few handful of information to make small changes based on some criteria. Using Openpyxl module, these tasks can be done very efficiently and easily.
    Use this command to install openpyxl module : 
     

    sudo pip3 install openpyxl 

     
    Input file : 
     

    Code #1 : Program to print the particular cell value 
     

    Python3

    import openpyxl

    path = "C:\Users\Admin\Desktop\demo.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 : 
     

    STUDENT 'S NAME

      
    Code #2 : Determine total number of rows 
     

    Python3

    import openpyxl

    path = "C:\Users\Admin\Desktop\demo.xlsx"

    wb_obj = openpyxl.load_workbook(path)

    sheet_obj = wb_obj.active

    print(sheet_obj.max_row)

    Output : 
     

    6

      
    Code #3 : Determine total number of columns 
     

    Python3

    import openpyxl

    path = "C:\Users\Admin\Desktop\demo.xlsx"

    wb_obj = openpyxl.load_workbook(path)

    sheet_obj = wb_obj.active

    print(sheet_obj.max_column)

    Output : 
     

    4

      
    Code #4 : Print all columns name 
     

    Python3

    import openpyxl

    path = "C:\Users\Admin\Desktop\demo.xlsx"

    wb_obj = openpyxl.load_workbook(path)

    sheet_obj = wb_obj.active

    max_col = sheet_obj.max_column

    for i in range(1, max_col + 1):

        cell_obj = sheet_obj.cell(row = 1, column = i)

        print(cell_obj.value)

    Output : 
     

    STUDENT 'S NAME
    COURSE
    BRANCH
    SEMESTER

      
    Code #5 : Print first column value 
     

    Python3

    import openpyxl

    path = "C:\Users\Admin\Desktop\demo.xlsx"

    wb_obj = openpyxl.load_workbook(path)

    sheet_obj = wb_obj.active

    m_row = sheet_obj.max_row

    for i in range(1, m_row + 1):

        cell_obj = sheet_obj.cell(row = i, column = 1)

        print(cell_obj.value)

    Output : 
     

    STUDENT 'S NAME
    ANKIT RAI
    RAHUL RAI
    PRIYA RAI
    AISHWARYA
    HARSHITA JAISWAL

      
    Code #6 : Print a particular row value 
     

    Python3

    import openpyxl

    path = "C:\Users\Admin\Desktop\demo.xlsx"

    wb_obj = openpyxl.load_workbook(path)

    sheet_obj = wb_obj.active

    max_col = sheet_obj.max_column

    for i in range(1, max_col + 1):

        cell_obj = sheet_obj.cell(row = 2, column = i)

        print(cell_obj.value, end = " ")

    Output : 
     

    ANKIT RAI B.TECH CSE 4

    Like Article

    Save Article

    Время на прочтение
    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.

    This is a comprehensive Python Openpyxl Tutorial to read and write MS Excel files in Python. Openpyxl is
    a Python module to deal with Excel files without involving MS Excel
    application software. It is used extensively in different operations
    from data copying to data mining and data analysis by computer
    operators to data analysts and data scientists. openpyxl is the most used module in python to handle excel files. If you have to read data from excel, or you want to write data or draw some charts, accessing sheets, renaming sheets, adding or deleting sheets, formatting and styling in sheets or any other task, openpyxl will do the job for you.

    If you want to Read, Write and Manipulate(Copy, cut, paste, delete or search for an item or value etc) Excel files in Python with simple and practical examples I will suggest you to see this simple and to the point

    Python Excel Openpyxl Course with examples about how to deal with MS Excel files in Python. This video course teaches efficiently how to manipulate excel files and automate tasks.

    Everything you do in Microsoft Excel, can be automated with Python. So why not use the power of Python and make your life easy. You can make intelligent and thinking Excel sheets, bringing the power of logic and thinking of Python to Excel which is usually static, hence bringing flexibility in Excel and a number of opportunities.

    Automate your Excel Tasks and save Time and Effort. You can save dozens or hundreds of hours by Python Excel Automation with just a single click get your tasks done with in seconds which used to take hours of Manual Excel and Data Entry Work.

    First
    we discuss some of the keywords used in Python excel relationship which
    are used in openpyxl programming for excel.

    Basics for Python excel openpyxl work:

    • An Excel file is usually called as Spreadsheet however in
      openpyxl we call it Workbook.
    • A single Workbook is usually saved in a file with extension
           .xlsx
    • A Workbook may have as less as one sheet and as many as
      dozens of worksheets.
    • Active sheet is the worksheet user is viewing or viewed
      before closing the file.
    • Each sheet consists of vertical columns, known as Column
      starting from A.
    • Each sheet consists of rows, called as Row. Numbering
      starts from 1.
    • Row and column meet at a box called Cell. Each cell has
      specific address in refrence to Row and Column. The cell may contain
      number, formula or text.
    • The grid of cells make the work area or worksheet in excel.

    The start: Reading data from an Excel sheet:

    Lets suppose we have this Excel file which we are going to use in our
    example. Its name is testfile.xlsx. You can either create a new excel
    file and fill in the data as it is shown in figure or download it and
    save it in your root folder. Mean the python folder in which all python
    files are located.

    Date Time Region Name Item Quantity Rate Total
    7/6/14 4:50 AM AB Connor Pencil 15 1.99 29.85
    4/23/14 2:25 PM DG Shane Binder 20 19.99 399.8
    5/9/14 4:45 AM PQ Thatcher Pencil 25 4.99 124.8
    13/26/2014 
    9:54:00 PM
    AR Gordon Pen 30 19.99 599.7
    3/15/14 6:00 AM TX James Pencil 35 2.99 104.7
    4/1/14 12:00 AM CA Jones Binder 40 4.99 199.6
    4/18/14 12:00 AM ND Stuart Pencil 45 1.99 89.55

    Sample file for reading. testfile.xlsx    Its better
    that you create excel file and fill in the same data.

    Now after downloading and installing openpyxl and after having this
    testfile in root folder lets get to the task.In case you don’t know
    what is your root directory for python. Type in the following code at
    prompt.


    >>>import os

    >>>os.getcwd(
    )

    We will import operating system, and then call function get current working directory  
               
     getcwd( )
    it will tell the current working directory for python, the result may
    be like that, as it is in my interpreter.

    ‘C:\Python34’

    Yes you are wise enough to know that I am using Python 3.4 for this
    tutorial.

    If you want to change the
    current working directory you can use the command    
       
    os.chdir( ). For example you have a file named abc.xlsx saved in myfiles folder which is in C: root directory, then you may use


    >>>os.ch.dir(«c:/myfiles»)

    With this code now you can work on files saved in myfiles directory on C drive. If you want to work with excel files in Python for a Live 1 on 1 Python Openpyxl Training you may

    contact us live 1 on 1 interactive Openpyxl training by an expert. Learn each and everything about how to deal with excel files in python like reading, writing, sorting, editing, making high quality graphs and charts in matplotlib.

    Opening excel files in Python:

    First we will import  openpyxl module with this statement

    >>>
    import openpyxl

    If there is no error message then it would mean openpyxl has been
    correctly installed and now it is available to work with Excel files.

    Next thing we are going to do is to load the Workbook testfile.xlsx
    with the help of following code


    >>>wb= openpyxl.load_workbook(‘testfile.xlsx’)

    openpyxl.load_workbook(‘testfile.xlsx’)  is a function. It
    takes the file name as parameter or argument and returns a workbook
    datatype. Workbook datatype infact represents the file just like as
    File object represents a text file that is opened. After loading the
    testfile.xlsx we will see what type of handle is available by typing

    >>type
    (wb)

    <class
    ‘openpyxl.workbook.workbook.Workbook’>

    The green colored line should be seen on the python shell. If you get
    this line up to here then all is well. Now a summary of commands we
    have typed with their output in python shell. Command typed by us is
    shown in blue, while response of interpreter is shown in green here and
    through out this tutorial.

    >>>
    import os

    >>>
    os.getcwd()

    ‘C:\Python34’
    >>>
    import openpyxl

    >>>
    wb=openpyxl.load_workbook(‘testfile.xlsx’)

    >>>
    type(wb)

    <class
    ‘openpyxl.workbook.workbook.Workbook’>

    >>>

    Openpyxl Tutorial for reading Excel Files

    Accessing sheets from the loaded workbook:

    We have to know the name of excel file to access it, now we can read
    and know about it more. To get information about the number of sheets
    in a workbook, and their names there is a function get_sheet_names( ).
    This function returns the names of the sheets in a workbook and you can
    count the names to tell about total number of sheets in current
    workbook. The code will be


    >>> wb.get_sheet_names()

    [‘Sheet1’,
    ‘Sheet2’, ‘Sheet3’]

    You can see that the function has returned three sheet names, which
    means the file has three sheets. Now you can do a little practice.
    Change the sheet names, save the file. Load the file again and see the
    results. We change the sheet names as      
       S1, S2, S3      
         and then save the Excel file. We have
    to load the file again so that changes appear in the response. We are
    creating a new workbook object. Code will remain same. Write in the
    following code.


    >>> wb=openpyxl.load_workbook(‘testfile.xlsx’)

    >>>
    wb.get_sheet_names()

    [‘S1,
    ‘S2’, ‘S3’]

    Now we see that sheet names are changed in output. You can practice a
    bit more. Please keep in mind, the more you work on this, the more you
    learn. Books and tutorials are for guidance, you have to be creative to
    master the art. Now change the sheet names to their orginal ones again.
    You will have to load the file once again for changes to take effect.

    After knowing names we can access any sheet at one time. Lets suppose
    we want to access Sheet3. Following code should be written


    >>> import openpyxl

    >>>
    wb=openpyxl.load_workbook(‘testfile.xlsx’)

    >>>
    wb.get_sheet_names()

    [‘Sheet1’,
    ‘Sheet2’, ‘Sheet3’]

    >>>
    sheet=wb.get_sheet_by_name(‘Sheet3’)

    the function get_sheet_by_name(‘Sheet3’)
    is used to access a particular sheet. This function takes the name of
    sheet as argument and returns a sheet object. We store that in a
    variable and can use it like…


    >>> sheet

    <Worksheet
    «Sheet3»>

    >>>
    type(sheet)

    <class
    ‘openpyxl.worksheet.worksheet.Worksheet’>

    >>>
    sheet.title

    ‘Sheet3’
    >>>

    if we write sheet
    it will tell which sheet is it pointing to, as in code, the shell
    replies with Worksheet «Sheet3».

    If we want to ask type of sheet object. type(sheet)

    It will tell what is the object sheet pointing to?

    >>>
    type(sheet)


    <class ‘openpyxl.worksheet.worksheet.Worksheet’>

    sheet.title tells the title of sheet that is referenced by sheet
    object.

    Some more code with sheet. If we want to access the active sheet. The
    interpreter will write the name of active sheet>

    >>>
    wb.active

    <Worksheet
    «Sheet1»>

    Accessing data in Cells of Worksheet:


    For accessing data from sheet cells we refer by sheet and then the cell
    address.

    >>>
    sheet[‘A2’].value

    datetime.datetime(2014,
    7, 6, 4, 50, 30)

    Another way of accessing cell data is like

    >>>
    e=sheet[‘B2’]

    >>>
    e.value

    ‘AB’
    >>>
    e.row

    2
    >>>
    e.column

    ‘B’
    >>>

    Getting data from cells with the help of rows and columns:


    >>> sheet.cell(row=2, column=4)

    <Cell
    Sheet1.D2>

    >>>
    sheet.cell(row=2, column=4).value

    ‘Pencil’

    Instead of getting one value from a column, now we print whole column,
    see the syntax. Ofcourse we will use iteration else we will have to
    write print statement again and again.
    For printing whole column the code will be


    >>> for x in range (1,9):

       
    print(x,sheet.cell(row=x,column=4).value)

       

    1
    Item

    2
    Pencil

    3
    Binder

    4
    Pencil

    5
    Pen

    6
    Pencil

    7
    Binder

    8
    Pencil

    >>>

     

    Now after printing the one complete column, what comes next? Print
    multiple columns, and as our file is a small one, we print all the
    columns here. See the code here.


    for y in range (1,9,1):

       
    print(sheet.cell(row=y,column=1).value,sheet.cell(row=y,column=2).value,

    sheet.cell(row=y,column=3).value,sheet.cell(row=y,column=4).value,
    sheet.cell(row=y,column=5).value, sheet.cell(row=y,column=6).value,
    sheet.cell(row=y,column=7).value,sheet.cell(row=y,column=8).value)

    This code will print all the columns in the worksheet. Hence upto now,
    we accessed an excel file, loaded it in memory, accessed sheets, and in
    the end accessed individual cells, keep tuned for next. (Professor M.N)

    If you want to Read, Write and Manipulate(Copy, cut, paste, delete or search for an item or value etc) Excel files in Python with simple and practical examples I will suggest you to see this simple and to the point

    Python Excel Openpyxl Course with examples about how to deal with MS Excel files in Python. This video course teaches efficiently how to manipulate excel files and automate tasks.

    Everything you do in Microsoft Excel, can be automated with Python. So why not use the power of Python and make your life easy. You can make intelligent and thinking Excel sheets, bringing the power of logic and thinking of Python to Excel which is usually static, hence bringing flexibility in Excel and a number of opportunities.

    Automate your Excel Tasks and save Time and Effort. You can save dozens or hundreds of hours by Python Excel Automation with just a single click get your tasks done with in seconds which used to take hours of Manual Excel and Data Entry Work.

    Now after reading Excel files in Python, its time to learn

    How to write to Excel Files in Python

    Понравилась статья? Поделить с друзьями:
  • Python excel date format
  • Python excel create sheet
  • Python excel cell value
  • Python opening excel files
  • Python excel cell merge