简体   繁体   English

如何在django中设置excel文件的路径

[英]how to set path for excel file in django

I'm using pandas ExcelWriter and openpyxl for creating excel in Django project. 我正在使用pandas ExcelWriter和openpyxl在Django项目中创建excel。 how would I set particular path in my project directory to save the created excel? 如何在项目目录中设置特定路径以保存创建的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 使用./path/to/file声明本地路径

UPDATE UPDATE

alternatively you can define the path in settings.py and then import it to any django file as 或者你可以在settings.py中定义路径,然后将其导入到任何django文件中

Settings.py: Settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Somewhere in Django: 在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: 可能最好的方法是将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

Then you can use a url that maps to this some_excelfile_view . 然后你可以使用一个url映射到这个some_excelfile_view If a user then visists that URL, it will perform a file download for the Excel file. 如果用户随后访问该URL,它将执行Excel文件的文件下载。

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 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM