Экспорт таблицы шаблона django в xlsx
I'm trying to use django template for the first time and I need to export some data. How can I export a table in my django template to a .xlsx file? Is there any method? here is my views.py:
from django.shortcuts import render
import requests
from .utils import most_frequent, get_json_values, get_max_dict
def launches(request):
"""main request. Retrieve the year that had most launches"""
response_launches = requests.get('https://api.spacexdata.com/v3/launches?
filter=launch_year')
launches = response_launches.json()
launch_years = get_json_values('launch_year',launches)
result_launches = most_frequent(launch_years)
"""retrieve the launch site most used for launches """
response_sites = requests.get('https://api.spacexdata.com/v3/launches?
filter=launch_site')
sites = response_sites.json()
launch_sites = get_json_values("launch_site", sites)
result_sites = get_max_dict(launch_sites,'site_id')
"""retrieve the number of launches between 2019 and 2021"""
response_2019_2021 = requests.get('https://api.spacexdata.com/v3/launches?
start=2019&end=2021')
launches_2019_2021 = response_2019_2021.json()
result_2019_2021 = len(launches_2019_2021)
data = {
"year_most_launches": str(result_launches),
"launch_sites":result_sites,
"launches_2019_2021":str(result_2019_2021)
}
return render(request,"main/launches.html", {"data":data})
А это моя таблица внутри моего шаблона:
<table class="table">
<thead>
<tr>
<th>Year with most launches</th>
<th>Launch site with most launches</th>
<th>Number of launches between 2019 and 2021</th>
</tr>
</thead>
<tbody>
<tr>
{% for element in data.values %}
<td>{{ element }}</td>
{% endfor %}
</tr>
</tbody>
</table>
Я не смог найти способ сделать это, поэтому любая помощь будет очень признательна!
В моем случае я создаю функцию в представлении, которая обрабатывает все данные и вставляет их в файл Excel. Позвольте мне дать вам код, он может помочь вам.
def export_excel(self, elements):
output = io.BytesIO()
workbook = Workbook(output, {'in_memory': True})
worksheet = workbook.add_worksheet()
# r = Row and c = Column
r = 0
c = 0
# Table header
table_headers = [
# Define your headers name here
''
]
for header in table_headers:
worksheet.write(r, c, header)
c += 1
r += 1
for element in elements:
# write your data in the excel following the same command
worksheet.write(r, 0, element.data_name)
r += 1
workbook.close()
output.seek(0)
content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response = HttpResponse(output.read(), content_type=content_type)
file_name = _('file_name')
response['Content-Disposition'] = "attachment; filename=" + file_name + ".xlsx"
return response
Дайте мне знать, если это было полезно