1.下载附件Excel
要下载xlsx模板文件
#views.py
from django.http import FileResponse
def file_down(request):
file=open('static/1.xlsx','rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="1.xlsx"'
return response
#urls.py
urlpatterns = [
......
path('file_down/',views.file_down,name='file_down'),
......
]
#设定static文件夹中要有附件excel。
#info.html
<p><a href="/myclass/file_down/">file_down</a></p>
#成功界面如下
2.下载Query_set的数据并作为Excel导出。
2.1 下载非Query_set的数据并作为Excel导出。
#views.py
# 下载excel数据
from openpyxl import Workbook,load_workbook
from io import BytesIO
def export_excel(request):
wb = Workbook()
sheet = wb.active
sheet.cell(row=1,column=1).value = '张三1'
sheet.cell(row=1,column=2).value = '李四1'
# 写出到IO
output = BytesIO()
wb.save(output)
# 设置HttpResponse的类型
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;filename=user.xlsx'
# 重新定位到开始
output.seek(0)
response.write(output.getvalue())
return response
2.2 string argument expected, got 'bytes’的解决方法
将StringIO改为BytesIO即可
将StringIO改为BytesIO即可
将StringIO改为BytesIO即可
链接
2.3 下载Query_set的数据并作为Excel导出。
#views.py
# 下载excel数据2
from openpyxl import Workbook,load_workbook
from io import BytesIO
def export_excel2(request):
wb = Workbook()
sheet = wb.active
# 导入数据库数据
i = 1
for Sub in Subject.objects.order_by('-Subject_id').all():
sheet.cell(row=i,column=1).value = Sub.Subject_id
sheet.cell(row=i,column=2).value = Sub.subject_name
sheet.cell(row=i,column=3).value = Sub.teacher.name
i = i+1
# 写出到IO
output = BytesIO()
wb.save(output)
# 设置HttpResponse的类型
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;filename=data.xlsx'
# 重新定位到开始
output.seek(0)
response.write(output.getvalue())
return response
#urls.py
urlpatterns = [
......
path('export_excel2/',views.export_excel2,name='export_excel2'),
......
]
#实际界面:将数据下载的功能嵌入已有的网页中,看下方index.html设定
#index.html
<html>
<head>
<title>notice</title>
</head>
<body>
<table>
<p>课程信息</p>
<tr align="center" style="color:White;background-color:#3366FF;font-family:微軟正黑體,Tahoma,Arial,微軟雅黑體;font-size:14px;">
<th scope="col">Subject_id</th>
<th scope="col">subject_name</th>
<th scope="col">teacher.name</th>
</tr>
{% for item in Subject_list %}
<tr align="center" valign="middle" style="color:Black;background-color:#EFF3FB;border-color:#E0E0E0;border-width:1px;border-style:solid;height:26px;">
<td>{{ item.Subject_id }}</td>
<td>{{ item.subject_name }}</td>
<td>{{ item.teacher.name }}</td>
</tr>
{% endfor %}
</table>
<p><a href="/myclass/export_excel2/">export_excel2</a></p>