Working With Excel Spread Sheets

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

EXCEL DOCUMENTS

First, let’s go over some basic definitions: An Excel spreadsheet document is


called a workbook. A single workbook is saved in a file with the .xlsx extension.
Each workbook can contain multiple sheets (also called worksheets). The sheet
the user is currently viewing (or last viewed before closing Excel) is called
the active sheet.

Each sheet has columns (addressed by letters starting at A) and rows (addressed


by numbers starting at 1). A box at a particular column and row is called a cell.
Each cell can contain a number or text value. The grid of cells with data makes up
a sheet.

INSTALLING THE OPENPYXL MODULE

Python does not come with OpenPyXL, so you’ll have to install it. Follow the
instructions for installing third-party modules in Appendix A; the name of the
module is openpyxl. To test whether it is installed correctly, enter the following
into the interactive shell:

>>> import openpyxl

If the module was correctly installed, this should produce no error messages.
Remember to import the openpyxl module before running the interactive shell
examples in this chapter, or you’ll get a NameError: name 'openpyxl' is not
defined error.

This book covers version 2.3.3 of OpenPyXL, but new versions are regularly
released by the OpenPyXL team. Don’t worry, though: New versions should stay
backward compatible with the instructions in this book for quite some time. If you
have a newer version and want to see what additional features may be available
to you, you can check out the full documentation for OpenPyXL
at http://openpyxl.readthedocs.org/.

READING EXCEL DOCUMENTS

The examples in this chapter will use a spreadsheet named example.xlsx stored in


the root folder. You can either create the spreadsheet yourself or download it
from http://nostarch.com/automatestuff/. Figure 12-1 shows the tabs for the
three default sheets named Sheet1, Sheet2, and Sheet3 that Excel automatically
provides for new workbooks. (The number of default sheets created may vary
between operating systems and spreadsheet programs.)

Figure 12-1. The tabs for a workbook’s sheets are in the lower-left corner of Excel.

Sheet 1 in the example file should look like Table 12-1. (If you didn’t
download example.xlsx from the website, you should enter this data into the
sheet yourself.)

Table 12-1. The example.xlsx Spreadsheet

  A B C
1 4/5/2015 1:34:02 PM Apples 73
2 4/5/2015 3:41:23 AM Cherries 85
3 4/6/2015 12:46:51 PM Pears 14
4 4/8/2015 8:59:43 AM Oranges 52
5 4/10/2015 2:07:00 AM Apples 152
6 4/10/2015 6:10:37 PM Bananas 23
7 4/10/2015 2:40:46 AM Strawberries 98

Now that we have our example spreadsheet, let’s see how we can manipulate it
with the openpyxl module.

OPENING EXCEL DOCUMENTS WITH OPENPYXL

Once you’ve imported the openpyxl module, you’ll be able to use


the openpyxl.load_workbook() function. Enter the following into the interactive
shell:
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>

The openpyxl.load_workbook() function takes in the filename and returns a value


of the workbook data type. This Workbook object represents the Excel file, a bit
like how a File object represents an opened text file.

Remember that example.xlsx needs to be in the current working directory in


order for you to work with it. You can find out what the current working directory
is by importing os and using os.getcwd(), and you can change the current working
directory using os.chdir().

GETTING SHEETS FROM THE WORKBOOK

You can get a list of all the sheet names in the workbook by calling
the get_sheet_names() method. Enter the following into the interactive shell:

>>> import openpyxl


>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet) <class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.active
>>> anotherSheet
<Worksheet "Sheet1">

Each sheet is represented by a Worksheet object, which you can obtain by passing


the sheet name string to the get_sheet_by_name() workbook method. Finally,
you can read the active member variable of a Workbook object to get the
workbook’s active sheet. The active sheet is the sheet that’s on top when the
workbook is opened in Excel. Once you have the Worksheet object, you can get its
name from the title attribute.

GETTING CELLS FROM THE SHEETS

Once you have a Worksheet object, you can access a Cell object by its name.
Enter the following into the interactive shell:

>>> import openpyxl


>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet['A1']
<Cell Sheet1.A1>
>>> sheet['A1'].value
datetime.datetime(2015, 4, 5, 13, 34, 2)
>>> c = sheet['B1']
>>> c.value
'Apples'
>>> 'Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value
'Row 1, Column B is Apples'
>>> 'Cell ' + c.coordinate + ' is ' + c.value
'Cell B1 is Apples'
>>> sheet['C1'].value
73

The Cell object has a value attribute that contains, unsurprisingly, the value stored


in that cell. Cell objects also have row, column, and coordinate attributes that
provide location information for the cell.

Here, accessing the value attribute of our Cell object for cell B1 gives us the


string 'Apples'. The row attribute gives us the integer 1, the column attribute gives
us 'B', and the coordinate attribute gives us 'B1'.

OpenPyXL will automatically interpret the dates in column A and return them
as datetime values rather than strings. The datetime data type is explained
further in Chapter 16.

Specifying a column by letter can be tricky to program, especially because after


column Z, the columns start by using two letters: AA, AB, AC, and so on. As an
alternative, you can also get a cell using the sheet’s cell() method and passing
integers for its row and column keyword arguments. The first row or column
integer is 1, not 0. Continue the interactive shell example by entering the
following:

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


<Cell Sheet1.B1>
>>> sheet.cell(row=1, column=2).value
'Apples'
>>> for i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)

1 Apples
3 Pears
5 Apples
7 Strawberries

As you can see, using the sheet’s cell() method and passing


it row=1 and column=2 gets you a Cell object for cell B1, just like
specifying sheet['B1'] did. Then, using the cell() method and its keyword
arguments, you can write a for loop to print the values of a series of cells.

Say you want to go down column B and print the value in every cell with an odd
row number. By passing 2 for the range() function’s “step” parameter, you can get
cells from every second row (in this case, all the odd-numbered rows).
The for loop’s i variable is passed for the row keyword argument to
the cell() method, while 2 is always passed for the column keyword argument.
Note that the integer 2, not the string 'B', is passed.

You can determine the size of the sheet with


the Worksheet object’s max_row and max_column member variables. Enter the
following into the interactive shell:

>>> import openpyxl


>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet.max_row
7
>>> sheet.max_column
3

Note that the max_column method returns an integer rather than the letter that
appears in Excel.

CONVERTING BETWEEN COLUMN LETTERS AND NUMBERS

To convert from letters to numbers, call


the openpyxl.cell.column_index_from_string() function. To convert from numbers
to letters, call the openpyxl.cell.get_column_letter() function. Enter the following
into the interactive shell:

>>> import openpyxl


>>> from openpyxl.cell import get_column_letter, column_index_from_string
>>> get_column_letter(1)
'A'
>>> get_column_letter(2)
'B'
>>> get_column_letter(27)
'AA'
>>> get_column_letter(900)
'AHP'
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> get_column_letter(sheet.max_column)
'C'
>>> column_index_from_string('A')
1
>>> column_index_from_string('AA')
27

After you import these two functions from the openpyxl.cell module, you can
call get_column_letter() and pass it an integer like 27 to figure out what the letter
name of the 27th column is. The function column_index_string() does the reverse:
You pass it the letter name of a column, and it tells you what number that column
is. You don’t need to have a workbook loaded to use these functions. If you want,
you can load a workbook, get a Worksheet object, and call a Worksheet object
method like max_column to get an integer. Then, you can pass that integer
to get_column_letter().

GETTING ROWS AND COLUMNS FROM THE SHEETS

You can slice Worksheet objects to get all the Cell objects in a row, column, or


rectangular area of the spreadsheet. Then you can loop over all the cells in the
slice. Enter the following into the interactive shell:

>>> import openpyxl


>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> tuple(sheet['A1':'C3'])
((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>), (<Cell Sheet1.A2>,
<Cell Sheet1.B2>, <Cell Sheet1.C2>), (<Cell Sheet1.A3>, <Cell Sheet1.B3>,
<Cell Sheet1.C3>))
❶ >>> for rowOfCellObjects in sheet['A1':'C3']:
❷ for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value)
print('--- END OF ROW ---')
A1 2015-04-05 13:34:02
B1 Apples
C1 73
--- END OF ROW ---
A2 2015-04-05 03:41:23
B2 Cherries
C2 85
--- END OF ROW ---
A3 2015-04-06 12:46:51
B3 Pears
C3 14
--- END OF ROW ---

Here, we specify that we want the Cell objects in the rectangular area from A1 to


C3, and we get a Generator object containing the Cell objects in that area. To help
us visualize this Generator object, we can use tuple() on it to display
its Cell objects in a tuple.
This tuple contains three tuples: one for each row, from the top of the desired
area to the bottom. Each of these three inner tuples contains the Cell objects in
one row of our desired area, from the leftmost cell to the right. So overall, our
slice of the sheet contains all the Cell objects in the area from A1 to C3, starting
from the top-left cell and ending with the bottom-right cell.

To print the values of each cell in the area, we use two for loops. The
outer for loop goes over each row in the slice ❶. Then, for each row, the
nested for loop goes through each cell in that row ❷.

To access the values of cells in a particular row or column, you can also use
a Worksheet object’s rows and columns attribute. Enter the following into the
interactive shell:

>>> import openpyxl


>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.active
>>> sheet.columns[1]
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>,
<Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
>>> for cellObj in sheet.columns[1]:
print(cellObj.value)

Apples
Cherries
Pears
Oranges
Apples
Bananas
Strawberries

Using the rows attribute on a Worksheet object will give you a tuple of tuples.


Each of these inner tuples represents a row, and contains the Cell objects in that
row. The columns attribute also gives you a tuple of tuples, with each of the inner
tuples containing the Cell objects in a particular column. For example.xlsx, since
there are 7 rows and 3 columns, rows gives us a tuple of 7 tuples (each containing
3 Cell objects), and columns gives us a tuple of 3 tuples (each containing
7 Cell objects).
To access one particular tuple, you can refer to it by its index in the larger tuple.
For example, to get the tuple that represents column B, you
use sheet.columns[1]. To get the tuple containing the Cell objects in column A,
you’d use sheet.columns[0]. Once you have a tuple representing one row or
column, you can loop through its Cell objects and print their values.

WORKBOOKS, SHEETS, CELLS

As a quick review, here’s a rundown of all the functions, methods, and data types
involved in reading a cell out of a spreadsheet file:

1. Import the openpyxl module.
2. Call the openpyxl.load_workbook() function.
3. Get a Workbook object.
4. Read the active member variable or call
the get_sheet_by_name() workbook method.
5. Get a Worksheet object.
6. Use indexing or the cell() sheet method with row and column keyword
arguments.
7. Get a Cell object.
8. Read the Cell object’s value attribute.

You might also like