# flask_返回字节流错误
def export_data(filename, fields, data, names=None, sheet=‘Sheet1‘):
# fields 为list data为dict
fp = io.BytesIO()
book = xlsxwriter.Workbook(fp, {‘in_memory‘: True})
worksheet = book.add_worksheet(sheet)
# 表头格式
format1 = book.add_format(
{‘bold‘: True, ‘font_color‘: ‘black‘, ‘font_size‘: 13, ‘align‘: ‘left‘, ‘font_name‘: u‘宋体‘})
# 表头外格式
format2 = book.add_format({‘font_color‘: ‘black‘, ‘font_size‘: 9, ‘align‘: ‘left‘, ‘font_name‘: u‘宋体‘})
# A列列宽设置能更好的显示
worksheet.set_column("A:F", 20)
# book = xlwt.Workbook()
# worksheet = book.add_sheet(‘Sheet1‘) # 创建一个sheet
# 插入第一行表头标题
if names:
for i in range(0, len(names)):
name = names[i]
worksheet.write(0, i, name, format1)
else:
for i in range(0, len(fields)):
field = fields[i]
worksheet.write(0, i, field, format2)
# 从第二行开始插入数据
for i in range(len(data)):
item = data[i]
for j in range(len(fields)):
field = fields[j]
worksheet.write(i + 1, j, item[field])
book.close()
# fp.seek(0)
# print(filename,‘////////////////////‘)
name = parse.quote(filename)
# print(fp.getvalue(),‘-------------------‘)
# rv = send_file(send_file(fp, attachment_filename=‘%s.xlsx‘ % name, as_attachment=True))
rv = make_response(fp.getvalue())
# 特别注意,必须加这一行
fp.close()
mime_type = mimetypes.guess_type(‘%s.xlsx‘ % name)[0]
rv.headers[‘Content-Type‘] = mime_type
rv.headers["Cache-Control"] = "no-cache"
rv.headers[‘Content-Disposition‘] = ‘attachment; filename={}.xlsx‘.format(name)
return rv
# 报错信息:
"""
io.UnsupportedOperation: fileno
....
/python3.6/site-packages/werkzeug/wsgi.py", line 893, in wrap_file
return environ.get(‘wsgi.file_wrapper‘, FileWrapper)(file, buffer_size)
SystemError: <built-in function uwsgi_sendfile> returned a result with an error set
原因:BytesIo未关闭,加上fp.close就行了
"""
原文地址:https://www.cnblogs.com/lajiao/p/9993790.html
时间: 2024-11-13 07:58:02