python - Pandas to openpyxl Workbook 以在 Flask 中下载文件
问题描述
目标是在 Excel 工作表中保存多个数据帧(每个数据帧作为一个工作表),并在用户点击指定的 URL 时下载文件。
这是代码。
@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
)
我收到以下错误。
AttributeError:“DatetimeArray”对象没有属性“tolist”
df1
有一个数据时间数据类型的列。我做了一些搜索,发现不建议迭代数据框,这导致了这个错误。
另一种方法是使用df.to_excel()
,但我不知道如何使它与 BytesIO 一起使用,因为我需要流式传输要下载的数据。
问题:如何将数据保存到 Excel 表并得到错误。
我必须使用send_file()
烧瓶来下载客户端上的文件。
解决方案
在附加到 Excel 表之前将数据时间 dtype 转换为字符串解决了该问题。可能有更好的解决方案,但这解决了我的问题
推荐阅读
- c# - 分页时 Azure Easy Tables 缺少和重复数据
- postgresql - SQL:如何获得数据库的全局概览
- sql - 尝试使用 OR 语句实现 2 个外连接。语法不正确?
- django - 如何在 Django DRF 的 GenericAPIView 中正确使用查询集?
- c - leetcode 38 的一个 c 解决方案 count and say 迷惑我
- c - 为什么指针数组的 free() 不会释放内存?
- java - log4j2 JSON 为根记录器配置多个附加程序
- regex - Fluentd 和 Docker
- ruby-on-rails - MyMethod 存在时 NoMethodError
- html - 如何在列图像上添加文本