在我的Django项目中,我需要将内存中的Excel文件发送到客户端进行下载。用户单击按钮后,应该开始下载。
这是我的项目结构:
C:.
│ db.sqlite3
│ manage.py
│ Pipfile
│ Pipfile.lock
│ requirements.txt
│
├───app
│ │ admin.py
│ │ apps.py
│ │ forms.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ __init__.py
│ │
│ └───templates
│ └───app
│ home.html
│
└───project
settings.py
urls.py
wsgi.py
__init__.py
我的app/forms.py
:
from django import forms
class HomeForm(forms.Form):
OPTIONS = (
('name', 'name'),
('city', 'city')
)
columns = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=OPTIONS)
我的app/views.py
:
from django.views.generic import TemplateView
from django.shortcuts import render
from app.forms import HomeForm
class HomeView(TemplateView):
template = 'app/home.html'
def get(self, request):
form = HomeForm()
return render(request, self.template, {'form': form})
这是我的app/urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomeView.as_view(), name="home"),
]
我的project/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('app.urls')),
path('admin/', admin.site.urls),
]
我的app/home.html
:
<!DOCTYPE html>
<html>
<head>
<title>Generate Data</title>
</head>
<body>
<form method="get">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Generate Excel">
</form>
</html>
</body>
我是Django的新手。如何以list
的形式获取列(名称,城市),创建字典{‘name’: [‘Bob’, ‘Tom’], ‘city’: [‘San Francisco’, ‘Atlanta’]}
,并在以下函数中使用字典,该函数创建内存中的Excel数据:
import pandas as pd
from io import BytesIO as IO
from django.http import HttpResponse
import xlsxwriter
def write_to_excel():
df_output = pd.DataFrame({'name': ['Bob', 'Tom'], 'city': ['San Francisco', 'Atlanta']})
# my "Excel" file, which is an in-memory output file (buffer)
# for the new workbook
excel_file = IO()
xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')
df_output.to_excel(xlwriter, 'sheetname')
xlwriter.save()
xlwriter.close()
# important step, rewind the buffer or when it is read() you'll get nothing
# but an error message when you try to open your zero length file in Excel
excel_file.seek(0)
# set the mime type so that the browser knows what to do with the file
response = HttpResponse(excel_file.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# set the file name in the Content-Disposition header
response['Content-Disposition'] = 'attachment; filename=myfile.xlsx'
return response
当用户单击Generate Excel
按钮时,应下载包含数据的Excel文件。我已经给出了所有这些代码,因为我认为有人需要帮助我。