Django2实现excel 文件的下载功能(xlsx文件)
时间: 2024-02-09 17:12:35 浏览: 73
要实现Django2的Excel文件下载功能,可以按照以下步骤进行:
1. 安装openpyxl库
```python
pip install openpyxl
```
2. 在views.py中编写生成Excel文件的函数
```python
import io
from django.http import FileResponse
from openpyxl import Workbook
def generate_excel(request):
# 获取数据
data = {...}
# 生成Excel文档
wb = Workbook()
ws = wb.active
# 添加表头
ws.append(['姓名', '年龄', '性别'])
# 添加数据
for item in data:
ws.append([item['name'], item['age'], item['gender']])
# 将Excel文档写入内存
output = io.BytesIO()
wb.save(output)
output.seek(0)
# 返回Excel文档
response = FileResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="example.xlsx"'
return response
```
3. 在urls.py中添加url
```python
from django.urls import path
from . import views
urlpatterns = [
path('generate-excel/', views.generate_excel, name='generate_excel'),
# ...
]
```
4. 在模板文件中添加Excel文件下载链接
```html
<a href="{% url 'generate_excel' %}">下载Excel文件</a>
```
在点击下载链接时,将会调用generate_excel函数生成Excel文件并下载。
阅读全文