使用pandas/openpyxl写入Excel文件会返回错误或创建需要修复的文件



我在2个月前的一个脚本中遇到了一个错误,这个脚本运行得很好。我首先用shutil.copyfile复制了一个Excel模板文件。到目前为止还不错。

然后我用pandas:创建了一个ExcelWriter类

writer = pd.ExcelWriter(out_xl, engine="openpyxl")
# some extra stuff for filling the file, 
# not relevant since the issue shows up with these 3 lines already
writer.save()
writer.close()

这曾经工作没有问题,但我现在收到这个错误:

IndexError: At least one sheet must be visible

添加附加模式:

writer = pd.ExcelWriter(out_xl, engine="openpyxl", mode="a")

删除了错误,但当我打开Excel文件时,我收到一条错误消息,说文件需要修复。

我使用Python 3.7、pandas 1.2.3和openpyxl 3.0.7。

知道出了什么问题吗?

编辑:

如果你想重现问题,复制/粘贴此代码:

import pandas as pd
from shutil import copyfile
template = r"path to any existing xlsx file"
out_xl = r"path to any xlsx file"
copyfile(template, out_xl)
writer = pd.ExcelWriter(out_xl, engine="openpyxl", mode="a")
writer.save()
writer.close()

我使用以下代码复制了一个Excel工作簿,打开它并将一个小数据框写入一个新的工作表

我没有显式保存和关闭复制的工作簿,而是使用了上下文管理器。

代码运行时没有错误,在代码完成后,我可以毫无问题地打开新工作簿

import pandas as pd
from pandas import ExcelWriter
from shutil import copyfile
template = r"test.xlsx"
out_xl = r"out.xlsx"
copyfile(template, out_xl)
df = pd.DataFrame({'col1':[1,2,3,4], 'col2':[5,6,7,9]})
with ExcelWriter(out_xl, mode="a", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="Sheet3")

最新更新