The openpyxl
module allows you to manipulate Excel sheets within Python. This is also includes file creation.
In [2]:
import openpyxl
The Workbook()
function creates an excel workbook.
In [4]:
wb = openpyxl.Workbook()
wb
Out[4]:
These workbooks are created with a default sheet, called 'Sheet'.
In [25]:
wb.get_sheet_names()
Out[25]:
In [7]:
sheet = wb.get_sheet_by_name('Sheet')
All the methods covered in Lesson 42 still apply, except all the cells are empty.
In [10]:
sheet['A1'].value
In [11]:
sheet['A1'].value == None
Out[11]:
We can now write values to these cells.
In [13]:
sheet['A1'].value = 42
sheet['A1'].value = 'Hello'
However, this spreadsheet only exists in the memory; it must be saved to be accessible in storage.
In [18]:
import os
# Navigate to the folder you want to save to, and confirm your path
os.chdir('files')
os.getcwd()
Out[18]:
We can now use the .save()
method on the Workbook object and provide a filename. Here, the filename is 'example2.xlsx'
In [20]:
wb.save('example2.xlsx')
It is recommended to save filenames with unique identifiers, so that they don't overwite existing files (example3, example4, etc.)
We can create new sheets with the .create_sheet()
method.
In [30]:
sheet2 = wb.create_sheet()
In [37]:
wb.get_sheet_names()
Out[37]:
Sheet names can be changed by editing the .title
value of a sheet object, or by passing that string to the .create_sheet()
method.
In [34]:
sheet2.title = 'My New Sheet Name'
# wb.create_sheet('My New Sheet Name')
openpyxl
) can also create Excel spreadsheet files (.xlsx
).openpyxl.Workbook()
creates a workbook object in memory..save()
method on the workbook with a string..create_sheet()
function and a string..title
parameter of a sheet object.