Quart自定义文件导出名
直接上代码
from quart import Quart, send_file import io import xlwt app = Quart(__name__) @app.route('/download-excel',methods=["POST"]) async def download_excel(): # 创建一个简单的 Excel 文件 workbook = xlwt.Workbook() sheet = workbook.add_sheet('Sheet1') # 写入一些示例数据 columns = ['Name', 'Age'] data = [ ['John', 28], ['Jane', 24], ['Doe', 22] ] for col_num, header in enumerate(columns): sheet.write(0, col_num, header) for row_num, row_data in enumerate(data, start=1): for col_num, cell_data in enumerate(row_data): sheet.write(row_num, col_num, cell_data) # 将工作簿保存到一个 BytesIO 对象 output = io.BytesIO() workbook.save(output) output.seek(0) # 使用 send_file 传递文件并指定文件名 return await send_file( output, as_attachment=True, attachment_filename ='ASADSDA.xlsx', mimetype='application/vnd.ms-excel' ) if __name__ == '__main__': app.run(debug=True)
如果还是不行尝试加上请求头:
data = await send_file(...) data.headers["Access-Control-Expose-Headers"] = 'Content-Disposition'
如果是乱码你可以将文件名进行转码或者加上以下请求头
from urllib.parse import quote filename = u'育种数据导出' + date_today + '.xlsx' encoded_filename = urllib.parse.quote(filename.encode('utf-8')) file = await send_file(output, mimetype='application/vnd.ms-excel', as_attachment=True, attachment_filename=encoded_filename) file.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"