加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

【django基础】django接口 异步ajax请求 导出数据库成excel表

发布时间:2020-12-15 17:09:05 所属栏目:大数据 来源:网络整理
导读:py文件: from django.utils.http import urlquote from rest_framework.views APIView from django.shortcuts render,redirect,HttpResponse from dal models from django.http JsonResponse,FileResponse,StreamingHttpResponse os xlwtBASE_DIR = os.path

py文件:

from django.utils.http import urlquote
from rest_framework.views  APIView
from django.shortcuts  render,redirect,HttpResponse
from dal  models
from django.http  JsonResponse,FileResponse,StreamingHttpResponse
 os

 xlwt

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # C:UsersuserDesktopDownTest



class fileShow(APIView):

    def get(self,request):

        message = {}
        userinfo = models.UserInfo.objects.all()

        workbook = xlwt.Workbook(encoding='utf-8')   新建工作簿

        sheet1 = workbook.add_sheet("用户表")   新建sheet
        sheet1.write(0,ID 第1行第1列数据
        sheet1.write(0,1,1)">用户名密码创建时间 第1行第1列数据

        path = BASE_DIR + utilsusername.xlsx"  储存路径

        excel_row = 1
        for obj in userinfo:
            data_id = obj.id
            data_username = obj.username
            data_password = obj.password
            data_time = obj.create_time

            sheet1.write(excel_row,data_id)
            sheet1.write(excel_row,1,data_username)
            sheet1.write(excel_row,2+= 1

            workbook.save(path)

        file = open(path,1)">rb')    字符串替换成文件
        print(file" file_names = file.name.split('/')[-1]
         print("file_names",file_names)

        response = FileResponse(file)
        response[Content-Type'] = application/octet-stream'

        response[Content-Dispositionattachment;filename={}".format(urlquote(path))  字符串替换成下载文件
        print(response)
        return response

html的ajax请求:

<button id=up">下载文件</button>  一个按钮


请求:

// 下载文件
    $(#up").on(click"down/get<a></a>);
                $a.attr(href",1)">"http://127.0.0.1:8000/down/);  # 红色的是你下载路径
                $(body).append($a);
                $a[0].click();
                $a.remove();
            }

        })

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读