我一直在我的Python / Flask应用上使用XLSXWriter将数据帧导出到Excel。直到今天,我设法在一个工作表上导出我的数据帧;现在我试图在一个文件中的不同工作表上导出多个数据帧。
当我在本地尝试时(请参阅附带的第一个代码),一切都很完美。但是当我写入IOStream时,我收到以下错误:
TypeError: invalid file: None
以下是功能本地代码:
path_user = expanduser("~").split("\\")[-1]
xlsx_path = r"C:\Users\{}\Desktop\ExportAllGraphs2.xlsx".format(path_user)
writer = pd.ExcelWriter(xlsx_path, engine='xlsxwriter')
count = 0
for df in df_list:
sheet_title = df["title"].split(' ', 1)[0]
sheet_name = "{}_{}".format(count, sheet_title)
df_header.to_excel(writer,startrow = 0, merge_cells = False, sheet_name = sheet_name)
df["df"].to_excel(writer,startrow = len(df_header) + 5, merge_cells = False, sheet_name = sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]
format = workbook.add_format()
format.set_bg_color('#eeeeee')
worksheet.set_column(0,50,20)
worksheet.write(len(df_header) + 4, 1, df["title"])
count += 1
writer.close()
os.system('start excel.exe "{}"'.format(xlsx_path))
这是无效的实时代码:
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
count = 0
for df in df_list:
sheet_title = df["title"].split(' ', 1)[0]
sheet_name = "{}_{}".format(count, sheet_title)
df_header.to_excel(writer,startrow = 0, merge_cells = False, sheet_name = sheet_name)
df["df"].to_excel(writer,startrow = len(df_header) + 5, merge_cells = False, sheet_name = sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]
format = workbook.add_format()
format.set_bg_color('#eeeeee')
worksheet.set_column(0,50,20)
worksheet.write(len(df_header) + 4, 1, df["title"])
count += 1
writer.close()
output.seek(0)
return send_file(output,
attachment_filename="test_export_{}.xlsx".format(current_date),
as_attachment=True)
我错过了什么吗?