我正在尝试使用 pandas 创建一个 Excel 文件,并通过 Django 将其作为可下载文件提供给用户。我就我在此处找到的主题整理了一些不同的答案,最后得到了这段代码:
collection = [{"title": "something", "price": 34, "quantity": 23}, {..}]
output = BytesIO()
df = pd.DataFrame(collection, columns=['title', 'price', 'quantity'])
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
output.seek(0)
workbook = output.getvalue()
response = StreamingHttpResponse(workbook, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={output_name}.xlsx'
return response
一切正常,直到我尝试打开生成的文件 - 我可能会出错,说文件已损坏或数据格式有问题。我怀疑它可能与二进制数据有关?我该如何解决这个问题?
解决方案
结果我不得不删除一些东西,所以代码现在看起来像这样并且工作正常:
collection = [{"title": "something", "price": 34, "quantity": 23}, {..}]
output = BytesIO()
df = pd.DataFrame(collection, columns=['title', 'price', 'quantity'])
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
output.seek(0)
# workbook = output.getvalue()
response = StreamingHttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = f'attachment; filename={output_name}.xlsx'
return response
慕慕森
潇潇雨雨
慕妹3146593
鸿蒙传说
相关分类