python 使用Openpyxl加载excel文件时出错

q5iwbnjs  于 2023-02-02  发布在  Python
关注(0)|答案(3)|浏览(677)

我正在尝试使用Python中的Openpyxl加载Excel文件。

from openpyxl import load_workbook 
    wb2 = load_workbook('Book1.xlsx')
    print wb2.get_sheet_names()

它只有这三行代码,并抛出以下错误:

Traceback (most recent call last):
  File "C:/Python27/excel1.py", line 5, in <module>
    wb2 = load_workbook('Book1.xlsx')
  File "C:\Python27\Lib\site-packages\openpyxl\reader\excel.py", line 141, in load_workbook
    archive = ZipFile(f, 'r', ZIP_DEFLATED)
  File "C:\Python27\Lib\zipfile.py", line 793, in __init__
    self._RealGetContents()
  File "C:\Python27\Lib\zipfile.py", line 835, in _RealGetContents
    raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file

这和他们的文档完全一样。https://openpyxl.readthedocs.org/en/latest/tutorial.html是他们更好的包吗?

csga3l58

csga3l581#

如果所需位置不存在此文件,请尝试:

from openpyxl import load_workbook
from openpyxl import Workbook

# 1) create a workbook
wb = Workbook()
wb.save('my.xlsx')
del wb
# 2) build connection with the just created excel
book = load_workbook('my.xlsx')
jjhzyzn0

jjhzyzn02#

这是文件的问题。当我们在外部保存文件时,它提示此错误。简单的修复方法是进行一次尝试捕获,如果它给出错误,则以相同的名称创建一个新文件并保存在相同的位置。但在这种情况下,追加旧数据将不起作用。

try:
    # this statement shall raise error for Badzip file
    wb_obj = openpyxl.load_workbook(filename=path)
except:
    # try to create a new file and save at same path
    wb_obj = openpyxl.Workbook()
    wb_obj.save(path)
    wb_obj = openpyxl.load_workbook(filename=path)
wz1wpwve

wz1wpwve3#

xlsx文件是zip存档。您试图打开的文件似乎不是。如果您认为不是这样,请提交一个示例文件。

相关问题