df.to_csv("output.csv", index=False)
OR
df.to_excel("output.xlsx")
Answer from mujjiga on Stack Overflowpython - how to download or convert dataframe into excel file? - Stack Overflow
python - django pandas dataframe download as excel file - Stack Overflow
I created an Excel Add-in to generate Pandas Dataframes right inside Excel
What's the fastest way to export a dataframe to an excel file?
df.to_csv("output.csv", index=False)
OR
df.to_excel("output.xlsx")
If you want to create multiple sheets in the same file
with pd.ExcelWriter('csv_s/results.xlsx') as writer:
same_res.to_excel(writer, sheet_name='same')
diff_res.to_excel(writer, sheet_name='sheet2')
The .to_excel method writes a file and returns None. If you want the file content encoded in base64, read it back in:
import pandas as pd
import base64
df = pd.DataFrame({'SourceNo':[11192,11193,11194],
'IssuedDate':['3/15/2021','3/15/2021','3/15/2021'],
'نوع':['هاتف','تلفاز','سماعة'],
'مكان الحدث':['حي السلم','منطقة الشمال','ميناء'],
'التاريخ':['3/15/2021','3/15/2021','3/15/2021'],
'أشخاص':['مواطنون','مواطنون','مجهول']})
df.to_excel('update2.xlsx', index = False, header=True,encoding='utf-8')
with open('update2.xlsx','rb') as f:
b64 = base64.b64encode(f.read())
to_excel method is used for exporting dataframe into an excel file. It is a void method, therefore it does not return anything. You try to get the return value into a variable named excel, and since the method does not return anything the excel variable is equal to None. That is the reason of the error.
As of pandas-0.17, you can let Django write to a BytesIO directly, like:
from django.http import HttpResponse
from io import BytesIO
def some_view(request):
with BytesIO() as b:
# Use the StringIO object as the filehandle.
writer = pd.ExcelWriter(b, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
# Set up the Http response.
filename = 'django_simple.xlsx'
response = HttpResponse(
b.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
You might need to install an Excel writer module (like xlsxwriter, or openpyxl).
I think it can be even simpler and more concise these days. You can just pass the http response directly to the Excel writer. The following works for me:
from django.http import HttpResponse
import pandas as pd
# df = CREATE YOUR OWN DATAFRAME
response = HttpResponse(content_type='application/xlsx')
response['Content-Disposition'] = f'attachment; filename="FILENAME.xlsx"'
with pd.ExcelWriter(response) as writer:
df.to_excel(writer, sheet_name='SHEET NAME')
return response