В моем проекте 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 с данными должен быть загружен.Я дал весь этот код, потому что думаю, что кто-то должен мне помочь.