简体   繁体   English

使用 openpyxl 编辑电子表格。 无法写入单元格,“单元格是只读错误”

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

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.我正在尝试使用 Openpyxl 修改 Python 中的 excel 工作表,但我不断收到错误消息,指出单元格是只读的。 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.我只是想了解使用 openpyxl 编辑工作表的方向,因此它是基本代码。

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?我应该为 python 使用不同的 excel 库吗? Is there a more robust excel library?有没有更强大的excel库?

Thanks!谢谢!

您正在以只读模式打开工作簿,这就是为什么单元格为只读的原因。

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.在回答中如前所述在这里,如果你通过use_iterators = True返回工作簿将是只读的。

In newer versions of openpyxl the use_iterators was renamed to read_only , eg:在较新版本的openpyxluse_iterators被重命名为read_only ,例如:

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 .因此,为了进行修改,您应该使用read_only = False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM