잡동사니

반응형

질문

사용자로부터 Excel 파일을 수락하고 pandas 데이터 프레임을 사용하여 몇 가지 작업을 수행해야합니다.

따라서 pandas를 사용하여 데이터 프레임을로드하려면 파일 경로를 전달해야합니다.

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

django에서는 HTML 입력 유형 파일을 사용하여 파일의 위치를 가져 오려고합니다. 그래야 pandas에서는 전달할 수 있지만 파이썬 변수에서는 파일 위치를 가져올 수 없습니다.

아래 코드를 시도했지만 변수에 경로를 저장하는 대신 html 페이지에 데이터를 print하고 있습니다.

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>

장고의 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 파일의 경로를 가져 오거나 pandas 데이터 프레임에서 Excel 데이터를로드 할 수있는 방법이 있습니까?


답변1

HTML에서 다음을 입력하십시오.

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

그런 다음 views.py에서 :

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


 

 

 

 

출처 : https://stackoverflow.com/questions/63048053/django-how-to-get-user-file-path

반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band