我使用openpyxl在python中使用excel文档。打开并保存文件后,我无法在文件管理器中打开它,它已经坏了。
workbook = openpyxl.load_workbook(path_to_tmp_xlsm)
workbook.save(path_to_tmp_xlsm)
print(path_to_tmp_xlsm)
我的错误:
list index out of range
ps这个脚本在Windows中工作正常,但在Linux下我有这个错误
Traceback (most recent call last):
File "/home/alex/projects/bokapi/Main.py", line 11, in <module>
class Main:
File "/home/alex/projects/bokapi/Main.py", line 12, in Main
EmailsDriveWorker()
File "/home/alex/projects/bokapi/app/EmailDriveWorker.py", line 33, in __init__
self.log_manager.save_all_companies_inf_log_to_gd()
File "/home/alex/projects/bokapi/app/EmailDriveWorker.py", line 202, in save_all_companies_inf_log_to_gd
path_to_xlsx = self.xmsl_box.update_log_file(log_list=logs, file=self.file)
File "/home/alex/projects/bokapi/xmsl/XmslBox.py", line 172, in update_log_file
workbook.save(path_to_tmp_xlsm)
File "/home/alex/projects/bokapi/venv/lib/python3.5/site-packages/openpyxl/workbook/workbook.py", line 367, in save
save_workbook(self, filename)
File "/home/alex/projects/bokapi/venv/lib/python3.5/site-packages/openpyxl/writer/excel.py", line 284, in save_workbook
writer.save(filename)
File "/home/alex/projects/bokapi/venv/lib/python3.5/site-packages/openpyxl/writer/excel.py", line 266, in save
self.write_data()
File "/home/alex/projects/bokapi/venv/lib/python3.5/site-packages/openpyxl/writer/excel.py", line 95, in write_data
archive.writestr(ARC_WORKBOOK, write_workbook(self.workbook))
File "/home/alex/projects/bokapi/venv/lib/python3.5/site-packages/openpyxl/writer/workbook.py", line 95, in write_workbook
wb.views[0].activeTab = active
IndexError: list index out of range
Process finished with exit code 1
答案 0 :(得分:2)
你(和我)似乎遇到了这个错误:Saving workbook gives IndexError on wb.views。 (还报告了here,但是因为OP无法重现而关闭了。)好消息是这个错误已经修复......两周前。我不知道它什么时候会出现在openpyxl的分布式版本中,但与此同时你可以解决这个问题:
wb = load_workbook("name.xlsx")
# Fix malformed workbook bug (gag)
if not wb.views:
wb.views.append(openpyxl.workbook.views.BookView())
我已验证wb.views
为空列表时发生错误。这只是添加了一个带默认值的新视图,Excel似乎很喜欢它。
PS。似乎某些文件只是不存储视图(或者如果它们存在,openpyxl
无法解析它。)在我的情况下,同一个脚本,在同一台计算机(OS X)上,在一个doc上工作并在另一个上失败。两个都是最后用Excel编辑的,但问题文件以前是用OpenOffice编写的;也许那是相关的。