django中实现excel的下载功能

利用python中的xlsxwriter库,注意该库只能创建excel.而不支持读取和修改,也不支持XLS格式。

1.urls.py

from django.contrib import admin
from django.urls import path, include
from web import views

urlpatterns = [
    path('download/',views.download),
  path('login/',views.login)
]

2.views.py

def download(request):
    document_root = settings.BASE_DIR
    dest_filename =  os.path.join(document_root,'files','xiao.xlsx')
    #dest_filename = document_root + 'files' + file_name
    wb = xlsxwriter.Workbook(dest_filename)
    print(wb)
    ws = wb.add_worksheet("xiashou")

    row_num = 0
    columns = ["序号",'姓名','年龄','密码']
    for colu_num in range(len(columns)):
        ws.write(row_num,colu_num,columns[colu_num])

    rows = User.objects.values_list('id','username','age','password')
    for row in rows:
        row_num += 1
        row = list(row)
        for colu_num in range(len(row)):
            ws.write(row_num,0,row[0])
            ws.write(row_num,1,row[1])
            ws.write(row_num,2,row[2])
            ws.write(row_num,3,row[3])
    wb.close()
    excel = open(dest_filename,'rb')
    response = FileResponse(excel)
    response["Content-Type"] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format('xiaoshou.xlsx')
    return response

def login(request):

return render(request, 'login.html')

3.login.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
</head>
<body>
<h1>hello world</h1>
    <button id="button">点我导出</button>
</div>
// 方法一:在浏览器中通过a标签
<div>
    <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" title="导出报表" href="/download/">导出报表</a>

</div>
<script type="text/javascript">
   // 方法二:通过ajax获取
    $('#button').click(function () {
        $.ajax({
            url: 'download/',
            type: 'get',
            dataType: 'application/octet-stream',
            success: function (res) {
                console.log("成功")
           }
        })
    })
</script>
</body>
</html>    
  1. 方法一:可以通过<a></a>标签来下载,href=‘/要跳转的路由/’;
  2. 方法二:通过ajax来去对应的路由进行下载;

更多关于xlsxwriter库,参考https://blog.csdn.net/qq_44670803/article/details/102776659

posted on 2022-11-20 14:03  一先生94  阅读(51)  评论(0编辑  收藏  举报

导航