[英]Pandas to openpyxl Workbook to download file in Flask
The goal is save multiple dataframes in Excel sheet (each dataframe as a sheet) and download the file when the user hit the specified URL.目标是在 Excel 工作表中保存多个数据框(每个数据框作为一个工作表),并在用户点击指定的 URL 时下载文件。
This is the code.这是代码。
@app.server.route("/file/excel")
def download_excel():
wb = Workbook()
df1 = pd.DataFrame(...)
sheet1 = wb.active
sheet1.title = "Sheet1"
for r in dataframe_to_rows(df1, index=False, header=True):
sheet1.append(r)
df2 = pd.DataFrame(...)
sheet2 = wb.active
sheet2.title = "Sheet1"
for r in dataframe_to_rows(df2, index=False, header=True):
sheet2.append(r)
excel_stream = io.BytesIO()
wb.save(excel_stream)
excel_stream.seek(0) # go to the beginning of the stream
#
return send_file(
excel_stream,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename="File.xlsx",
as_attachment=True,
cache_timeout=0
)
I am getting the following error.我收到以下错误。
AttributeError: 'DatetimeArray' object has no attribute 'tolist' AttributeError: 'DatetimeArray' 对象没有属性 'tolist'
df1
has a column with datatime data type. df1
有一列数据时间数据类型。 I did some search and found out that iterating through dataframe is not advised and that is causing this error.我做了一些搜索,发现不建议遍历数据帧,这导致了这个错误。
The alternative is to use df.to_excel()
, but I don't know how to make it work with BytesIO as I need to stream the data to be downloaded.另一种方法是使用df.to_excel()
,但我不知道如何使其与 BytesIO 一起使用,因为我需要流式传输要下载的数据。
Question: how can I save the data to the excel sheet and get the error.问题:如何将数据保存到excel表中并得到错误。 I have to use send_file()
for flask to download the file on the client.我必须使用send_file()
为烧瓶下载客户端上的文件。
Converting the datatime dtype to string before appending to the excel sheet resolved the issue.在附加到 Excel 工作表之前将 datatime dtype 转换为字符串解决了该问题。 There might be a better solution, but this solved my issue可能有更好的解决方案,但这解决了我的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.