Reputation: 81
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!
Upvotes: 3
Views: 3682
Reputation: 36
If you want to edit a read-only file, you can set read_only
to false
:
file_path = 'test.xlsx'
wb = openpyxl.load_workbook(file_path, read_only=False)
Upvotes: 0
Reputation: 1658
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
.
Upvotes: 2
Reputation: 19527
You are opening the workbook in read-only mode which is why the cells are read-only.
Upvotes: 1