Python excel openpyxl запись в ячейку

I wrote code which opens an excel file and iterates through each row and passes the value to another function.

import openpyxl
wb = load_workbook(filename='C:Usersxxxxx')
for ws in wb.worksheets:
    for row in ws.rows:
        print row
        x1=ucr(row[0].value)
        row[1].value=x1  #  i am having error at this point

I am getting the following error when I tried to run the file.

TypeError: IndexError: tuple index out of range

Can I write the returned value x1 to the row[1] column. Is it possible to write to excel (i.e using row[1]) instead of accessing single cells like ws.['c1']=x1

ballade4op52's user avatar

ballade4op52

2,2374 gold badges25 silver badges41 bronze badges

asked Jul 13, 2015 at 23:15

Priyaranjan's user avatar

1

Try this:

import openpyxl
wb = load_workbook(filename='xxxx.xlsx')
ws = wb.worksheets[0]
ws['A1'] = 1
ws.cell(row=2, column=2).value = 2

This will set Cells A1 and B2 to 1 and 2 respectively (two different ways of setting cell values in a worksheet).

The second method (specifying row and column) is most useful for your situation:

import openpyxl
wb = load_workbook(filename='xxxxx.xlsx')
for ws in wb.worksheets:
    for index, row in enumerate(ws.rows, start=1):
        print row
        x1 = ucr(row[0].value)
        ws.cell(row=index, column=2).value = x1

answered Jul 13, 2015 at 23:22

Jake Griffin's user avatar

Jake GriffinJake Griffin

1,95412 silver badges15 bronze badges

6

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

Python Excel tutorial openpyxl install

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.

python excel readin excel openpyxl

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:

empty spreadsheet using Python

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:

python excel writing to file

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:

append data excel python

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:

append data excel python

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:

finding sum excel python

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:

adjusting rows and columns excel python

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:

merge cells excel python

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:

unmerge cells excel python

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:

setting style excel python

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:

create chart excel python

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:

create chart excel python 2

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:

add image excel python

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?

In this article you will learn how to write to a workbook cell in Python using Openpyxl. There are three ways in Openpyxl to write to a cell, with sheet reference, with cell reference and with row and column number.

Writing to individual cell of Excel sheet in Python with Openpyxl
module has become very easy with code continuously evolving and
becoming simpler. When using python if you want to write to individual
cell or cells with openpyxl module, there are technically three
methods. However, before starting writing to a cell here are the steps
that must be performed in order to successfuly write data to individual
cells.

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.

Steps to write data to a cell

1. For using openpyxl, its necessary to import it

>>>import
openpyxl

2. Next step is to create a workbook object

>>>myworkbook=openpyxl.load_workbook(path)

3. Create a reference to the sheet on which you want to write. Lets say
you want to write on Sheet 1

>>>worksheet=
myworkbook.get_sheet_by_name(‘Sheet1’)

Example: Openpyxl Write to Cell — 3 Ways

Now after creating a reference to sheet we can easily write to cells.
As stated earlier there are three methods.

Write to a cell with sheet reference

First method is to use sheet reference and write the cell address
i.e C5, D8, F16 etc.

>>>worksheet[‘B4′]=’We
are writing to B4’

Write to a cell with cell reference

Second method is to create a reference to cell with the help of
sheet reference and then use that reference to write to cell with cell
address

>>>mycell=worksheet[‘B4’]

>>>mycell.value=’Writing
with reference to cell’

Write to a cell with Row and Column Number

Third method is to use row and column number and use worksheet
reference to create reference to cell and then write to that cell. This
method is extremely helpful for writing to a large number of cells one
by one as it can use loops, like for loop very efficiently. If you want
to write to E4 then the row is 4 and column is 5th in Excel.

>>>mycell=
mysheet.cell(row=4, column=5)    

>>>mycell=’Writing
data to E4′

Using a loop to write to a series of cells picking values from a list.

>>>for
i in range(5,15):

   
       
cellref=mysheet.cell(row=i, column=5)

   
       
cellref.value=lista[i]

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 с помощью Openpyxl. Пришло время узнать, как делать запись данных в Excel с помощью Openpyxl.

И конечно же — все просто 😉
Смотрим на код ниже:

import openpyxl #Подключаем библиотеку Openpyxl
wb = openpyxl.load_workbook(‘testfile.xlsx’) #Открываем тестовый Excel файл
wb.create_sheet(‘Sheet1’) #Создаем лист с названием «Sheet1»
worksheet = wb[‘Sheet1’] #Делаем его активным
worksheet[‘B4′]=’We are writing to B4’ #В указанную ячейку на активном листе пишем все, что в кавычках
wb.save(‘testdel.xlsx’) #Сохраняем измененный файл

  1. import openpyxl #Подключаем библиотеку Openpyxl
  2. wb = openpyxl.load_workbook('testfile.xlsx') #Открываем тестовый Excel файл
  3. wb.create_sheet('Sheet1') #Создаем лист с названием "Sheet1"
  4. worksheet = wb['Sheet1'] #Делаем его активным
  5. worksheet['B4']='We are writing to B4' #В указанную ячейку на активном листе пишем все, что в кавычках
  6. wb.save('testdel.xlsx') #Сохраняем измененный файл

Больше …

Привет всем! В прошлой записи мы рассматривали вариант создания страницы…

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

Модуль OpenPyXL не поставляется вместе с Python, поэтому его предварительно нужно установить:

> pip install openpyxl

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

Начинаем работать:

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>
>>> wb.sheetnames
['Лист1', 'Лист2', 'Лист3']
>>> sheet = wb.active
>>> sheet
<Worksheet "Лист1">
>>> sheet['A1']
<Cell Лист1.A1>

А теперь небольшой скрипт:

import openpyxl

# читаем excel-файл
wb = openpyxl.load_workbook('example.xlsx')

# печатаем список листов
sheets = wb.sheetnames
for sheet in sheets:
    print(sheet)

# получаем активный лист
sheet = wb.active

# печатаем значение ячейки A1
print(sheet['A1'].value)
# печатаем значение ячейки B1
print(sheet['B1'].value)

Результат работы:

Лист1
Лист2
Лист3

2015-04-05 13:34:02
Яблоки

Как получить другой лист книги:

# получаем другой лист
sheet2 = wb['Лист2']
# печатаем значение ячейки A1
print(sheet2['A2'].value)

Как сделать лист книги активным:

# делаем третий лист активным
wb.active = 2

Как задать имя листа:

sheet.title = 'Третий лист'

Объект Cell имеет атрибут value, который содержит значение, хранящееся в ячейке. Объект Cell также имеет атрибуты row, column и coordinate, которые предоставляют информацию о расположении данной ячейки в таблице.

# получаем ячейку листа B2
cell = sheet['B2']
print('Строка: ' + str(cell.row))
print('Столбец: ' + cell.column)
print('Ячейка: ' + cell.coordinate)
print('Значение: ' + cell.value)
Строка: 2
Столбец: B
Ячейка: B2
Значение: Вишни

К отдельной ячейке можно также обращаться с помощью метода cell() объекта Worksheet, передавая ему именованные аргументы row и column. Первому столбцу или первой строке соответствует число 1, а не 0:

# получаем ячейку листа B2
cell = sheet.cell(row = 2, column = 2)
print(cell.value)
Вишни

Размер листа можно получить с помощью атрибутов max_row и max_column объекта Worksheet:

rows = sheet.max_row
cols = sheet.max_column

for i in range(1, rows + 1):
    string = ''
    for j in range(1, cols + 1):
        cell = sheet.cell(row = i, column = j)
        string = string + str(cell.value) + ' '
    print(string)
2015-04-05 13:34:02 Яблоки 73 
2015-04-05 03:41:23 Вишни 85 
2015-04-06 12:46:51 Груши 14 
2015-04-08 08:59:43 Апельсины 52 
2015-04-10 02:07:00 Яблоки 152 
2015-04-10 18:10:37 Бананы 23 
2015-04-10 02:40:46 Земляника 98

Чтобы преобразовать буквенное обозначение столбца в цифровое, следует вызвать функцию

openpyxl.utils.column_index_from_string()

Чтобы преобразовать цифровое обозначение столбуа в буквенное, следует вызвать функцию

openpyxl.utils.get_column_letter()

Для вызова этих функций загружать рабочую книгу не обязательно.

>>> from openpyxl.utils import get_column_letter, column_index_from_string
>>> get_column_letter(1)
'A'
>>> get_column_letter(27)
'AA'
>>> column_index_from_string('A')
1
>>> column_index_from_string('AA')
27

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

>>> sheet['A1':'C3']
((<Cell 'Лист1'.A1>, <Cell 'Лист1'.B1>, <Cell 'Лист1'.C1>),
 (<Cell 'Лист1'.A2>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.C2>),
 (<Cell 'Лист1'.A3>, <Cell 'Лист1'.B3>, <Cell 'Лист1'.C3>))
for row in sheet['A1':'C3']:
    string = ''
    for cell in row:
        string = string + str(cell.value) + ' '
    print(string)
2015-04-05 13:34:02 Яблоки 73 
2015-04-05 03:41:23 Вишни 85 
2015-04-06 12:46:51 Груши 14 

Выводим значения второй колонки:

>>> sheet['B']
(<Cell 'Лист1'.B1>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.B3>, <Cell 'Лист1'.B4>, ..., <Cell 'Лист1'.B7>)
for cell in sheet['B']:
    print(cell.value)
Яблоки
Вишни
Груши
Апельсины
Яблоки
Бананы
Земляника

Выводим строки с первой по третью:

>>> sheet[1:3]
((<Cell 'Лист1'.A1>, <Cell 'Лист1'.B1>, <Cell 'Лист1'.C1>),
 (<Cell 'Лист1'.A2>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.C2>),
 (<Cell 'Лист1'.A3>, <Cell 'Лист1'.B3>, <Cell 'Лист1'.C3>))
for row in sheet[1:3]:
    string = ''
    for cell in row:
        string = string + str(cell.value) + ' '
    print(string)
2015-04-05 13:34:02 Яблоки 73 
2015-04-05 03:41:23 Вишни 85 
2015-04-06 12:46:51 Груши 14 

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

>>> list(sheet.rows)
[(<Cell 'Лист1'.A1>, <Cell 'Лист1'.B1>, <Cell 'Лист1'.C1>),
 (<Cell 'Лист1'.A2>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.C2>),
 ..........
 (<Cell 'Лист1'.A6>, <Cell 'Лист1'.B6>, <Cell 'Лист1'.C6>),
 (<Cell 'Лист1'.A7>, <Cell 'Лист1'.B7>, <Cell 'Лист1'.C7>)]
for row in sheet.rows:
    print(row)
(<Cell 'Лист1'.A1>, <Cell 'Лист1'.B1>, <Cell 'Лист1'.C1>)
(<Cell 'Лист1'.A2>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.C2>)
..........
(<Cell 'Лист1'.A6>, <Cell 'Лист1'.B6>, <Cell 'Лист1'.C6>)
(<Cell 'Лист1'.A7>, <Cell 'Лист1'.B7>, <Cell 'Лист1'.C7>)
>>> list(sheet.columns)
[(<Cell 'Лист1'.A1>, <Cell 'Лист1'.A2>, <Cell 'Лист1'.A3>, <Cell 'Лист1'.A4>, ..., <Cell 'Лист1'.A7>),
 (<Cell 'Лист1'.B1>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.B3>, <Cell 'Лист1'.B4>, ..., <Cell 'Лист1'.B7>),
 (<Cell 'Лист1'.C1>, <Cell 'Лист1'.C2>, <Cell 'Лист1'.C3>, <Cell 'Лист1'.C4>, ..., <Cell 'Лист1'.C7>)]
for column in sheet.columns:
    print(column)
(<Cell 'Лист1'.A1>, <Cell 'Лист1'.A2>, <Cell 'Лист1'.A3>, <Cell 'Лист1'.A4>, ..., <Cell 'Лист1'.A7>)
(<Cell 'Лист1'.B1>, <Cell 'Лист1'.B2>, <Cell 'Лист1'.B3>, <Cell 'Лист1'.B4>, ..., <Cell 'Лист1'.B7>)
(<Cell 'Лист1'.C1>, <Cell 'Лист1'.C2>, <Cell 'Лист1'.C3>, <Cell 'Лист1'.C4>, ..., <Cell 'Лист1'.C7>)

Выводим значения всех ячеек листа:

for row in sheet.rows:
    string = ''
    for cell in row:
        string = string + str(cell.value) + ' '
    print(string)
2015-04-05 13:34:02 Яблоки 73 
2015-04-05 03:41:23 Вишни 85 
2015-04-06 12:46:51 Груши 14 
2015-04-08 08:59:43 Апельсины 52 
2015-04-10 02:07:00 Яблоки 152 
2015-04-10 18:10:37 Бананы 23 
2015-04-10 02:40:46 Земляника 98 

Выводим значения второй строки (индекс 1):

for cell in list(sheet.rows)[1]:
    print(str(cell.value))
2015-04-05 03:41:23
Вишни
85

Выводим значения второй колонки (индекс 1):

for row in sheet.rows:
    print(str(row[1].value))
Яблоки
Вишни
Груши
Апельсины
Яблоки
Бананы
Земляника

Запись файлов Excel

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> wb.sheetnames
['Sheet']
>>> wb.create_sheet(title = 'Первый лист', index = 0)
<Worksheet "Первый лист">
>>> wb.sheetnames
['Первый лист', 'Sheet']
>>> wb.remove(wb['Первый лист'])
>>> wb.sheetnames
['Sheet']
>>> wb.save('example.xlsx')

Метод create_sheet() возвращает новый объект Worksheet, который по умолчанию становится последним листом книги. С помощью именованных аргументов title и index можно задать имя и индекс нового листа.

Метод remove() принимает в качестве аргумента не строку с именем листа, а объект Worksheet. Если известно только имя листа, который надо удалить, используйте wb[sheetname]. Еще один способ удалить лист — использовать инструкцию del wb[sheetname].

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

Запись значений в ячейки напоминает запись значений в ключи словаря:

>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> wb.create_sheet(title = 'Первый лист', index = 0)
>>> sheet = wb['Первый лист']
>>> sheet['A1'] = 'Здравствуй, мир!'
>>> sheet['A1'].value
'Здравствуй, мир!'

Заполняем таблицу 3×3:

import openpyxl

# создаем новый excel-файл
wb = openpyxl.Workbook()

# добавляем новый лист
wb.create_sheet(title = 'Первый лист', index = 0)

# получаем лист, с которым будем работать
sheet = wb['Первый лист']

for row in range(1, 4):
    for col in range(1, 4):
        value = str(row) + str(col)
        cell = sheet.cell(row = row, column = col)
        cell.value = value

wb.save('example.xlsx')

Можно добавлять строки целиком:

sheet.append(['Первый', 'Второй', 'Третий'])
sheet.append(['Четвертый', 'Пятый', 'Шестой'])
sheet.append(['Седьмой', 'Восьмой', 'Девятый'])

Стилевое оформление

Для настройки шрифтов, используемых в ячейках, необходимо импортировать функцию Font() из модуля openpyxl.styles:

from openpyxl.styles import Font

Ниже приведен пример создания новой рабочей книги, в которой для шрифта, используемого в ячейке A1, устанавливается шрифт Arial, красный цвет, курсивное начертание и размер 24 пункта:

import openpyxl
from openpyxl.styles import Font

# создаем новый excel-файл
wb = openpyxl.Workbook()
# добавляем новый лист
wb.create_sheet(title = 'Первый лист', index = 0)
# получаем лист, с которым будем работать
sheet = wb['Первый лист']

font = Font(name='Arial', size=24, italic=True, color='FF0000')
sheet['A1'].font = font
sheet['A1'] = 'Здравствуй мир!'

# записываем файл
wb.save('example.xlsx')

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

import openpyxl
from openpyxl.styles import NamedStyle, Font, Border, Side

# создаем новый excel-файл
wb = openpyxl.Workbook()
# добавляем новый лист
wb.create_sheet(title = 'Первый лист', index = 0)
# получаем лист, с которым будем работать
sheet = wb['Первый лист']

# создаем именованный стиль
ns = NamedStyle(name='highlight')
ns.font = Font(bold=True, size=20)
border = Side(style='thick', color='000000')
ns.border = Border(left=border, top=border, right=border, bottom=border)

# вновь созданный именованный стиль надо зарегистрировать
# для дальнейшего использования
wb.add_named_style(ns)

# теперь можно использовать именованный стиль
sheet['A1'].style = 'highlight'

# записываем файл
wb.save('example.xlsx')

Добавление формул

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

sheet['B9'] = '=SUM(B1:B8)'

Эта инструкция сохранит =SUM(B1:B8) в качестве значения в ячейке B9. Тем самым для ячейки B9 задается формула, которая суммирует значения, хранящиеся в ячейках от B1 до B8.

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

Использование ссылок на ячейки позволяет пересчитывать результат по формулам, когда происходят изменения содержимого ячеек, включенных в формулы. Формулы Excel начинаются со знака =. Скобки () могут использоваться для определения порядка математических операции.

Примеры формул Excel: =27+36, =А1+А2-АЗ, =SUM(А1:А5), =MAX(АЗ:А5), =(А1+А2)/АЗ.

Хранящуюся в ячейке формулу можно читать, как любое другое значение. Однако, если нужно получить результат расчета по формуле, а не саму формулу, то при вызове функции load_workbook() ей следует передать именованный аргумент data_only со значением True.

Настройка строк и столбцов

С помощью модуля OpenPyXL можно задавать высоту строк и ширину столбцов таблицы, закреплять их на месте (чтобы они всегда были видны на экране), полностью скрывать из виду, объединять ячейки.

Настройка высоты строк и ширины столбцов

Объекты Worksheet имеют атрибуты row_dimensions и column_dimensions, которые управляют высотой строк и шириной столбцов.

sheet['A1'] = 'Высокая строка'
sheet['B2'] = 'Широкий столбец'

sheet.row_dimensions[1].height = 70
sheet.column_dimensions['B'].width = 30

Атрибуты row_dimensions и column_dimensions представляют собой значения, подобные словарю. Атрибут row_dimensions содержит объекты RowDimensions, а атрибут column_dimensions содержит объекты ColumnDimensions. Доступ к объектам в row_dimensions осуществляется с использованием номера строки, а доступ к объектам в column_dimensions — с использованием буквы столбца.

Для указания высоты строки разрешено использовать целые или вещественные числа в диапазоне от 0 до 409. Для указания ширины столбца можно использовать целые или вещественные числа в диапазоне от 0 до 255. Столбцы с нулевой шириной и строки с нулевой высотой невидимы для пользователя.

Объединение ячеек

Ячейки, занимающие прямоугольную область, могут быть объединены в одну ячейку с помощью метода merge_cells() рабочего листа:

sheet.merge_cells('A1:D3')
sheet['A1'] = 'Объединены двенадцать ячеек'

sheet.merge_cells('C5:E5')
sheet['C5'] = 'Объединены три ячейки'

Чтобы отменить слияние ячеек, надо вызвать метод unmerge_cells():

sheet.unmerge_cells('A1:D3')
sheet.unmerge_cells('C5:E5')

Закрепление областей

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

У объекта Worksheet имеется атрибут freeze_panes, значением которого может служить объект Cell или строка с координатами ячеек. Все строки и столбцы, расположенные выше и левее, будут заблокированы.

Значение атрибута freeze_panes Заблокированные строки и столбцы
sheet.freeze_panes = 'A2' Строка 1
sheet.freeze_panes = 'B1' Столбец A
sheet.freeze_panes = 'C1' Столбцы A и B
sheet.freeze_panes = 'C2' Строка 1 и столбцы A и B
sheet.freeze_panes = None Закрепленные области отсутствуют

Диаграммы

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

  1. создать объект Reference на основе ячеек в пределах выделенной прямоугольной области;
  2. создать объект Series, передав функции Series() объект Reference;
  3. создать объект Chart;
  4. дополнительно можно установить значения переменных drawing.top, drawing.left, drawing.width, drawing.height объекта Chart, определяющих положение и размеры диаграммы;
  5. добавить объект Chart в объект Worksheet.

Объекты Reference создаются путем вызова функции openpyxl.charts.Reference(), принимающей пять аргуменов:

  1. Объект Worksheet, содержащий данные диаграммы.
  2. Два целых числа, представляющих верхнюю левую ячейку выделенной прямоугольной области, в которых содержатся данные диаграммы: первое число задает строку, второе — столбец; первой строке соответствует 1, а не 0.
  3. Два целых числа, представляющих нижнюю правую ячейку выделенной прямоугольной области, в которых содержатся данные диаграммы: первое число задает строку, второе — столбец.
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

# создаем новый excel-файл
wb = Workbook()
# добавляем новый лист
wb.create_sheet(title = 'Первый лист', index = 0)
# получаем лист, с которым будем работать
sheet = wb['Первый лист']

sheet['A1'] = 'Серия 1'
# это колонка с данными
for i in range(1, 11):
    cell = sheet.cell(row = i + 1, column = 1)
    cell.value = i * i

# создаем диаграмму
chart = BarChart()
chart.title = 'Первая серия данных'
data = Reference(sheet, min_col = 1, min_row = 1, max_col = 1, max_row = 11)
chart.add_data(data, titles_from_data = True)

# добавляем диаграмму на лист
sheet.add_chart(chart, 'C2')

# записываем файл
wb.save('example.xlsx')

Аналогично можно создавать графики, точечные и круговые диаграммы, вызывая методы:

  • openpyxl.chart.LineChart()
  • openpyxl.chart.ScatterChart()
  • openpyxl.chart.PieChart()

Поиск:
Excel • MS • Python • Web-разработка • Модуль

Introduction

In previous article, “Use openpyxl — create a new Worksheet, change sheet property in Python”, I introduced how to create a new Worksheet and change Worksheet properties.

In this article I show how to read and write Cell in Excel with Python.

Enter values to Cell

Worksheet object has a position of Cell as property. That is dictionary type and consists of row and column number.
Using them, access to Cell and edit the values. A sample code is as below.

 1from openpyxl import Workbook
 2from openpyxl.compat import range
 3from openpyxl.utils import get_column_letter
 4
 5wb = Workbook()
 6ws = wb.active
 7
 8# Enter `hogehogehoge` in column of `B` and row of `2`
 9ws['B2'] = 'hogehogehoge'
10# Enter `fugafugaufga` in column of `F` and row of `5`
11ws['F5'] = 'fugafugaufga'
12
13wb.save(filename = 'sample_book.xlsx')

fill_cell

Or, using cell function can do the same. However, cell function must be given arguments column number and line number.

1ws.cell(row=2, column=2, value='hogehogehoge')
2ws.cell(row=5, column=6, value='fugafugaufga')

Read values in Cell

To read values in Cell, access to value property in Cell object.

Or, using cell function can do the same when reading.

1b2 = ws.cell(column=2, row=2).value

Processing for each row

The iter_rows function can get instances for each row.
For specifying to range of extracting data, min_row, max_row, min_col and max_col options exist.
In addition, if max_row or max_col options are not given in arguments, it is the processing target up to the position where the data is entered.

Actually, it’s rarely to read datas from column A of the first row when handling files.

In the following example, processing in units of one line with the second line as the starting line.

1for row in ws.iter_rows(min_row=2):
2    for cell in row:
3        print(f"col {cell.col_idx}{cell.value}")
4    print('------------------------------------------')

The output result is as follows.

 1col 1None
 2col 2hogehogehoge
 3col 3None
 4col 4None
 5col 5None
 6col 6None
 7------------------------------------------
 8col 1None
 9col 2None
10col 3None
11col 4None
12col 5None
13col 6None
14------------------------------------------
15col 1None
16col 2None
17col 3None
18col 4None
19col 5None
20col 6None
21------------------------------------------
22col 1None
23col 2None
24col 3None
25col 4None
26col 5None
27col 6fugafugaufga
28------------------------------------------

Processing for each column

The iter_cols function can get instances for each column.
Usage is similar to iter_rows function.

In the following example, processing in units of one column with the second column as the starting column.

1for col in ws.iter_cols(min_row=2):
2    for cell in col:
3        print(f"row {cell.row}{cell.value}")
4    print('------------------------------------------')

The output result is as follows.

 1row 2None
 2row 3None
 3row 4None
 4row 5None
 5------------------------------------------
 6row 2hogehogehoge
 7row 3None
 8row 4None
 9row 5None
10------------------------------------------
11row 2None
12row 3None
13row 4None
14row 5None
15------------------------------------------
16row 2None
17row 3None
18row 4None
19row 5None
20------------------------------------------
21row 2None
22row 3None
23row 4None
24row 5None
25------------------------------------------
26row 2None
27row 3None
28row 4None
29row 5fugafugaufga
30------------------------------------------

Enter values for a row

The append function in Worksheet instance can enter data for one row.
By giving list type data as an argument, data goes into the sheet left-aligned.

 1wb = Workbook()
 2ws = wb.active
 3
 4data = [
 5        ['A', 100, 1.0],
 6        ['B', 200, 2.0],
 7        ['C', 300, 3.0],    
 8        ['D', 400, 4.0],        
 9]
10
11for row in data:
12    ws.append(row)
13
14wb.save(filename = 'sample_book.xlsx')

bulk_insert

Conclusion

It is available to

  • Enter or read values to Cell with Cell instance property or cell function
  • Process data row by row or colum
  • Enter a value for a row with append function

В этом уроке я расскажу, как создать файл 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)

Понравилась статья? Поделить с друзьями:
  • Python pandas csv to excel
  • Python excel insert row
  • Python pandas create excel
  • Python excel for windows
  • Python pandas and excel