I'm using pandas ExcelWriter and openpyxl
for creating excel in Django project. how would I set particular path in my project directory to save the created excel? thanks, in advance.
from pandas import ExcelWriter
df_view = obj_master.get_employee()
writer = ExcelWriter('PythonExportt.xlsx')
df_view.to_excel(writer, 'Sheet1')
writer.save()
use ./path/to/file
to declare a local path
UPDATE
alternatively you can define the path in settings.py and then import it to any django file as
Settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Somewhere in Django:
from django.conf import settings
def write_to_excel(dataFrame, sheetName):
writer = pd.ExcelWriter(settings.BASE_DIR, engine='xlsxwriter')
dataFrame.to_excel(writer, sheetName='Sheet1')
writer.save()
Probably the best way is to write the Pandas Excel stream to a memory stream, and then wrap this into a HTTP response:
from pandas import ExcelWriter
XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
def some_excelfile_view(request):
response = HttpResponse(content_type=XLSX_MIME)
response['Content-Disposition'] = 'attachment; filename="PythonExport.xlsx"'
# obtain obj_master
# ...
writer = pd.ExcelWriter(, engine='xlsxwriter')
df_view = obj_master.get_employee()
df_view.to_excel(writer, 'Sheet1')
writer.save()
return response
Then you can use a url
that maps to this some_excelfile_view
. If a user then visists that URL, it will perform a file download for the Excel file.
To get the path of the project directory, regardless of any constraint. The settings.py
has the value of the project directory in BASE_DIR
, you should import it and save the file
from myproject.settings import BASE_DIR
from pandas import ExcelWriter
import os
save_path = os.path.join(BASE_DIR, 'backup')
df_view = obj_master.get_employee()
writer = ExcelWriter('{}/PythonExportt.xlsx'.format(save_path))
df_view.to_excel(writer, 'Sheet1')
writer.save()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.