原文链接:http://www.juzicode.com/python-error-worksheet-sheet-does-not-exist
错误提示:
openpyxl打开表格sheet页时提示KeyError: ‘Worksheet sheet does not exist.’
#juzicode.com/VX公众号:juzicode
from openpyxl import load_workbook
wb = load_workbook('profile.xlsx')
ws = wb['sheet']
vals = []
for row in ws.iter_rows(values_only=True): # 迭代读出
vals.append(row)
print(row)
==========运行结果:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[9], line 4
2 from openpyxl import load_workbook
3 wb = load_workbook('profile.xlsx')
----> 4 ws = wb['sheet']
5 vals = []
6 for row in ws.iter_rows(values_only=True): # 迭代读出
File D:\Python\Python310\lib\site-packages\openpyxl\workbook\workbook.py:287, in Workbook.__getitem__(self, key)
285 if sheet.title == key:
286 return sheet
--> 287 raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: 'Worksheet sheet does not exist.'
错误原因:
1、提示名称为“sheet”的工作表不存在
解决方法:
1、原文件工作表的名称为“Sheet”,但是代码中的工作表名称为”sheet“,首字母大小写不一样,所以提示表格不存在,需要修改和文件一样即可。
#juzicode.com/VX公众号:juzicode
from openpyxl import load_workbook
wb = load_workbook('profile.xlsx')
ws = wb['Sheet']
vals = []
for row in ws.iter_rows(values_only=True): # 迭代读出
vals.append(row)
print(row)
扩展内容:
如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。