我想创建一个Web框架工作我想上传excel文件,然后保存并下载相同的excel文件。如果相同的excel文件上传2或3次或更多,下载此文件应该用一些sumbers命名?使用下载按钮我该怎么做
我已经编写了上传代码,但我不确定如何继续下载部分可以任何人帮助
Views.py
from django.shortcuts import render
import openpyxl
import settings
def index(request):
if "GET" == request.method:
return render(request, 'myapp/index.html', {})
else:
excel_file = request.FILES["excel_file"]
# you may put validations here to check extension or file size
wb = openpyxl.load_workbook(excel_file)
# getting all sheets
sheets = wb.sheetnames
print(sheets)
# getting a particular sheet
worksheet = wb["Sheet1"]
print(worksheet)
# getting active sheet
active_sheet = wb.active
print(active_sheet)
# reading a cell
print(worksheet["A1"].value)
excel_data = list()
# iterating over the rows and
# getting value from each cell in row
for row in worksheet.iter_rows():
row_data = list()
for cell in row:
row_data.append(str(cell.value))
print(cell.value)
excel_data.append(row_data)
return render(request, 'myapp/index.html', {"excel_data":excel_data})
index .html
<html>
<head>
<title>
Excel file upload and processing : Django Example : ThePythonDjango.Com
</title>
</head>
<body style="margin-top: 30px;margin-left: 30px;">
<form action="{% url "myapp:index" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file"
title="Upload excel file"
name="excel_file"
style="border: 1px solid black; padding: 5px;"
required="required">
<p>
<input type="submit"
value="Upload"
style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;">
</form>
<p></p>
<hr>
{% for row in excel_data %}
{% for cell in row %}
{{ cell }}
{% endfor %}
<br>
{% endfor %}
</body>
</html>
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls', namespace="myapp")),
]
答案 0 :(得分:0)
当多次上传同一文件时,新文件将使用扩展编号或随机字符串命名。你可以调整它。
有两种方法可以下载文件:
将上传的文件存储在公共场所,然后使用webserver(nginx,apache)处理下载。就像你使用webserver为Django项目提供静态/媒体文件一样。这是推荐的。看看这个:Deploying static files
在django视图中,读取文件的内容,然后将其返回给客户端。不建议这样做。