4 回答

TA貢獻1856條經驗 獲得超17個贊
我認為您可能會使它變得比需要的復雜得多。
以下對我來說很好用:
import pandas as pd
from django.http import HttpResponse
df = pd.DataFrame(data)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="filename.xlsx"'
df.to_excel(response)
return response

TA貢獻1833條經驗 獲得超4個贊
解決方案
結果我不得不刪除一些東西,所以代碼現在看起來像這樣并且工作正常:
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

TA貢獻1820條經驗 獲得超9個贊
AI 建議:):
import pandas as pd
from django.http import HttpResponse
df = pd.DataFrame(data)
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="my_data.xlsx"'
df.to_excel(response, index=False)
return response

TA貢獻1865條經驗 獲得超7個贊
在 Excel 中打開時可能是數據類型問題,請嘗試將數據轉換為字符串,然后創建 excel 并嘗試。
另一個想法是使用一組樣本記錄創建文件,而不是整個框架來驗證它是否是數據問題。數據集中的 Nan's 也可能存在問題。檢查您是否需要忽略/轉換/替換它。
添加回答
舉報