保存工作簿时出现 KeyError
Posted
技术标签:
【中文标题】保存工作簿时出现 KeyError【英文标题】:KeyError when saving workbook 【发布时间】:2019-05-27 11:30:55 【问题描述】:文件 transactions.xlsx 没有更新,这正是由于 add_chart()。如果我注释掉 add_chart 所有这些错误都不会出现,但我想绘制图表,这是我知道的唯一方法。 transanctions2.xlsx 文件已创建,但已损坏,而确实出现了一堆错误。
from openpyxl.chart import BarChart, Reference
wb1 = xl.load_workbook('transactions.xlsx')
sheet = wb1['Sheet1']
cell = sheet.cell(1, 1)
for row in range(2, sheet.max_row + 1):
cell = sheet.cell(row, 3)
corrected_price = cell.value * 0.9
corrected_price_cell = sheet.cell(row, 4)
corrected_price_cell.value = corrected_price
values = Reference(sheet,
min_row=2,
max_row=sheet.max_row,
min_col=4,
max_col=4)
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, 'f2')
wb1.save('transactions2.xlsx')
Traceback (most recent call last):
File "C:/Users/Saman/PycharmProjects/Excel/excel_edit.py", line 23, in <module>
wb1.save('transactions2.xlsx')
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 397, in save
save_workbook(self, filename)
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 294, in save_workbook
writer.save()
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 276, in save
self.write_data()
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 76, in write_data
self._write_worksheets()
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 219, in _write_worksheets
self._write_drawing(ws._drawing)
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\writer\excel.py", line 142, in _write_drawing
self._archive.writestr(drawing.path[1:], tostring(drawing._write()))
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 283, in _write
anchor = _check_anchor(obj)
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\drawing\spreadsheet_drawing.py", line 224, in _check_anchor
row, col = coordinate_to_tuple(anchor)
File "C:\Users\Saman\PycharmProjects\Excel\venv\lib\site-packages\openpyxl\utils\cell.py", line 201, in coordinate_to_tuple
return int(row), _COL_STRING_CACHE[col]
KeyError: 'f'
【问题讨论】:
【参考方案1】:命名列时大小写很重要 - 具体来说,它们是大写的:
sheet.add_chart(chart, 'F2')
我将f
更改为F
。
【讨论】:
百万感谢和祈祷你刚刚解决了我的问题我为此睡了一晚我正在学习 python,我知道这个错误是多么愚蠢。很抱歉为这样一个愚蠢的错误浪费您的时间【参考方案2】:只是为了加起来
查看他们的docs
你应该使用大写
sheet.add_chart(chart, 'F2')
【讨论】:
以上是关于保存工作簿时出现 KeyError的主要内容,如果未能解决你的问题,请参考以下文章
在同一活动工作簿中从一个工作表复制和粘贴到另一个工作表时出现错误 1004