利用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

原文地址:http://www.cnblogs.com/shaoyishi/p/16908372.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性