Using openpyxl to edit a spreadsheet. Cannot write to cells, "cell is read-only error"

3.2k views Asked by At

I'm trying to modify an excel worksheet in Python with Openpyxl, but I keep getting an error that says the cells are read only. I know for a fact that they are not because I've been editing these spreadsheets manually for the past two months and have had no issues. Does anyone have an idea of what might be happening? I'm just trying to get my bearings on editing sheets with openpyxl so it is basic code.

rpt = file
workbook = openpyxl.load_workbook(filename = os.path.join('./Desktop/',rpt), use_iterators = True) # Tells which wb to open
wb=workbook
#worksheets = wb.get_sheet_names() 
ws = wb.active
ws['A1'] = 42

Any help will be greatly appreciated. Thanks!

Thanks for the responses, to clarify, I'm not getting a workbook is read only error, it is specifically referring to the cells. I'm not sure what's causing this since I know that the workbook is not a read only workbook. Should I be using a different excel library for python? Is there a more robust excel library?

Thanks!

2

There are 2 answers

3
Charlie Clark On

You are opening the workbook in read-only mode which is why the cells are read-only.

0
Martin Gergov On

In case any other desperate soul is searching for a solution:

As stated in an answer here if you pass use_iterators = True the returned workbook will be read-only.

In newer versions of openpyxl the use_iterators was renamed to read_only, e.g.:

import openpyxl


rpt = file
workbook = openpyxl.load_workbook(filename = os.path.join('./Desktop/',rpt), read_only = True) # Tells which wb to open
wb=workbook
#worksheets = wb.get_sheet_names() 
ws = wb.active
ws['A1'] = 42

Will yield:

TypeError: 'ReadOnlyWorksheet' object does not support item assignment

So in order to do the modification you should use read_only = False.