Python Data Persistence – Creating a workbook

Python Data Presistence – Creating a workbook

An object of the Workbook class represents an empty workbook with one worksheet. Set it to be active so that data can be added to it.

Example

>>> from openpyxl import Workbook
>>> wb=Workbook( )
>>> sheet1=wb.active
>>> sheetl.title='PriceList'

Each cell in the worksheet is identified by a string made of Column name and row number. The top-left cell is ‘A1’. The normal assignment operator is used to storing data in a cell.

>>> sheet1['A1']='Hello World'

(NB: These operations as well as others that will be described in this chapter will not be immediately visualized in the Python environment itself. The workbook so created needs to be saved and then opened using Excel application to see the effect)

There is another way to assign value to a cell. The cell( ) method accepts row and column parameters with integer values. Column names A, B, C, and so on; will be denoted by 1,2,3, and so on. Rows are also numbered from 1.

>>> sheet1.cell(row=1, column=1).value='Hello World'

Contents of cells are retrieved from their value attribute.

>>> sheet1['a1'].value 
'Hello World'

Use the save ( ) method to store the workbook object as an Excel document. Later, open it to verify the above process, (figure 10.2)

Python Data Presistence - Creating a workbook chapter 10 img 1