我正在使用熊猫ExcelWriter和openpyxl
在Django项目中创建Excel。如何在项目目录中设置特定路径以保存创建的Excel?谢谢,谢谢。
from pandas import ExcelWriter
df_view = obj_master.get_employee()
writer = ExcelWriter('PythonExportt.xlsx')
df_view.to_excel(writer, 'Sheet1')
writer.save()
答案 0 :(得分:1)
使用./path/to/file
声明本地路径
更新
或者,您可以在settings.py中定义路径,然后将其作为
导入到任何django文件中。Settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
在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()
答案 1 :(得分:1)
最好的方法可能是将Pandas Excel流写入内存流,然后将其包装到HTTP响应中:
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(response, engine='xlsxwriter')
df_view = obj_master.get_employee()
df_view.to_excel(writer, 'Sheet1')
writer.save()
return response
然后,您可以使用映射到此url
的{{1}}。如果用户随后访问该URL,它将为Excel文件执行文件下载。
答案 2 :(得分:1)
获取项目目录的路径,而不受任何约束。 settings.py
在BASE_DIR
中具有项目目录的值,您应该导入它并保存文件
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()