OpenPyXL

suggest change

OpenPyXL is a module for manipulating and creating xlsx/xlsm/xltx/xltm workbooks in memory.

Manipulating and reading an existing workbook:

import openpyxl as opx
#To change an existing workbook we locate it by referencing its path
workbook = opx.load_workbook(workbook_path)

load_workbook() contains the parameter read_only, setting this to True will load the workbook as read_only, this is helpful when reading larger xlsx files:

workbook = opx.load_workbook(workbook_path, read_only=True)

Once you have loaded the workbook into memory, you can access the individual sheets using workbook.worksheets. workbook_path is not defined in these snippets.

first_sheet = workbook.worksheets[0]

If you want to specify the name of an available sheet, the code below uses workbook.get_sheet_by_name(). In current openpyxl that name is deprecated in favor of workbook[name], and workbook.sheetnames replaces get_sheet_names().

sheet = workbook.get_sheet_by_name('Sheet Name')

Finally, the rows of the sheet can be accessed using sheet.rows. To iterate over the rows in a sheet, use:

Since each row in rows is a tuple of Cells, use Cell.value to get the contents of the Cell. The loop that was supposed to follow “use:” is not on the page. openpyxl was not installed, and these samples were not run.

Creating a new Workbook in memory:

#Calling the Workbook() function creates a new book in memory
wb = opx.Workbook()

#We can then create a new sheet in the wb
ws = wb.create_sheet('Sheet Name', 0) #0 refers to the index of the sheet order in the wb

Several tab properties may be changed through openpyxl, for example the tabColor:

ws.sheet_properties.tabColor = 'FFC0CB'

To save our created workbook we finish with:

wb.save('filename.xlsx')

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents