Django-如何获取用户文件路径?

时间:2020-07-23 06:19:29

标签: python django pandas django-forms

我必须接受用户的excel文件,并使用pandas数据框对其执行一些操作。

因此要使用熊猫加载数据框,我需要传递文件路径:

fd =pd.read_excel('C:\users\chan\desktop\abc.xlsx')

在django中,我试图使用 HTML输入类型文件来获取文件的位置,以便我可以在pandas中传递它,但无法在python变量中获取文件位置。

我尝试了下面的代码,但它在html页面上打印数据,而不是将其路径存储在变量中:

HTML:

<html>
    <head>
        <title>Coordinates to Bounding Box</title>
    </head>
    <body>
        <form  method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    </form>
    {% block content %}
        <h3>File uploaded successfully</h3>
        {{file.name}}
        </br>content = {{contentOfFile}}
    {% endblock %}
    </body>
</html>

Django的views.py

from django.shortcuts import render
from django.conf.urls.static import static
from django.http import HttpResponse


# Create your views here.
def index(request):    
    if request.method == 'POST':
        file1 = request.FILES['file']
        contentOfFile = file1.read()
        if file1:
            return render(request, 'index.html', {'file': file1, 'contentOfFile': contentOfFile})
    return render(request,'index.html')

有什么办法可以获取excel文件的路径或将excel数据加载到pandas数据框中吗?

1 个答案:

答案 0 :(得分:0)

在您输入的html中:

<input type="file" name="excel_file" accept=".xlsx">

然后在views.py中输入

excel_file = request.FILES.get('excel_file')
df = pd.read_excel(excel_file)