fra*_*lis 7 python excel openpyxl
图书馆有更新吗?
之前还可以正常使用,今天更新后就无法加载了
我搜索过但找不到其他选项
看起来开发人员的新建议是使用临时文件: https://openpyxl.readthedocs.io/en/3.1/tutorial.html ?highlight=save# saving-as-a-stream
更新:我最终不得不使用它进行修改
from tempfile import NamedTemporaryFile
from openpyxl import Workbook
wb = Workbook()
with NamedTemporaryFile() as tmp:
tmp.close() # with statement opened tmp, close it so wb.save can open it
wb.save(tmp.name)
with open(tmp.name, 'rb') as f:
f.seek(0) # probably not needed anymore
new_file_object = f.read()
Run Code Online (Sandbox Code Playgroud)
因为该with语句打开文件,然后wb.save(需要一个string filename)尝试打开它,导致Exception
官方建议在 Windows 上不起作用(按原样),它使用文件系统来保存工作簿,即使只是短暂保存。
这是我心中更好的方法,它全部都在内存中:
with io.BytesIO() as buffer:
wb.save(buffer)
content = buffer.getvalue()
Run Code Online (Sandbox Code Playgroud)
这是可行的,因为这里ZipFile()使用的底层除了文件名之外还接受类似文件的对象。