我正在尝试将压缩文件夹中的 excel 文件发送回用户的浏览器。
我使用 openpyxl 构建 excel 文件,这是我的代码:
@app.route('/test', methods=['GET', 'POST'])
def test():
# ...
from zipfile import ZipFile
# ...
buf = BytesIO()
wb.save(buf)
buf.seek(0)
with ZipFile(buf, 'w') as myzip:
myzip.write(buf, arcname='test.xlsx')
return send_file(myzip, attachment_filename='folder.zip', as_attachment=True)
但是,我收到以下错误:
类型错误:统计:路径应该是字符串,字节,操作系统。路径相似或整数,而不是_io。字节IO
如何在不使用 bytesio 对象的情况下执行此操作? 或者我可以修改代码以容纳 bytesio 对象吗?
提前非常感谢。
试试这段代码。
@app.route('/test', methods=['GET', 'POST'])
def test():
# ...
from zipfile import ZipFile
# ...
buf = BytesIO()
wb.save(buf)
buf.seek(0)
filename = 'folder.zip' # assuing zip file u need
with ZipFile(filename, 'w') as myzip:
myzip.writestr(zinfo_or_arcname='test.xlsx', bytes=buf.read())
return send_file(myzip, attachment_filename='folder.zip', as_attachment=True)
更改,使用writestr
而不是write
filename = 'folder.zip' # assuing zip file u need
with ZipFile(filename, 'w') as myzip:
myzip.writestr(zinfo_or_arcname='test.xlsx', bytes=buf.read())