我是靠谱客的博主 搞怪雨,最近开发中收集的这篇文章主要介绍django 一键生成excel表格并下载到本地,并根据时间删除文件,上传excel文件,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

from django.http.response import HttpResponse, JsonResponse
import datetime
import os
import xlwt
import xlrd
from django.http import StreamingHttpResponse
    def Export_excel(request):#生成EXCEL表格
        if request.method=='POST':
            try:
                now = datetime.datetime.now()
                file_path = os.path.join(r'static/excel/','%s.xlsx'%now.strftime("%Y-%m-%d-%H-%M-%S"))                                                                                  
                f=list(os.listdir(mailpath)) 
#列出实例化的路径下面的文件(根据时间只保留最新创建的excel文件,其中mailpath填写自己的excel保存路径http://blog.51cto.com/net881004/2052066)

                    for i in range(len(f)):            #len统计多少个文件,然后循环赋值给变量i。
                        maildate = os.path.getmtime(mailpath + f[i])  #获取每个文件的时间的时间
                        currdate = time.time()         #当前时间
                        num1 =(currdate - maildate)/60     #当前时间减去文件时间,然后换成乘天。
                        if num1 > 0:
                        try:
                            os.remove(mailpath + f[i])
                        except Exception as e:
                            print(e)
                wb = xlwt.Workbook(encoding='utf-8')#开始创建excel
                LST_test = wb.add_sheet(now.strftime("%m-%d"))#excel中的表名
                LST_test.write(0, 0, '编号')    #列名
                LST_test.write(0, 1, '用户id')
                LST_test.write(0, 2, '创建时间')
                row = 1
                datas =[#要用到的数据] 
                for i in datas:
                    LST_test.write(row, 0, int(i.id))#row为每一行要添加的数据,0为第几列,最后的是要添加的数据
                    LST_test.write(row, 1, i.user_id_id)
                    LST_test.write(row, 2, i.create_time.strftime("%Y-%m-%d %H:%M:%S"))
                    row = row + 1
                wb.save(file_path)#保存
                return JsonResponse({'code':0,'data':file_path})#将路径返回到前台
            except  Exception as e:
                print(e)
                return JsonResponse({'code': 1, 'data': '导出表格失败!'})

#这里是前台html代码

function Export_excel(arg){
$.ajax({
    url:'/Export_excel/',
    type:'post',
    data:{},#自己要传的数据
    success:function(arg){
        if (arg.code===0){
            window.location.href='/download?data='+arg.data+'';
        }else{
            alert(arg.data)
        }
    },error:function(){
        alert('导出失败');
    }
})
}

#下载的方法

Django的HttpResponse对象允许将迭代器作为传入参数,将上面代码中的传入参数c换成一个迭代器,便可以将上述下载功能优化为对大小文件均适合;而Django更进一步,推荐使用StreamingHttpResponse对象取代HttpResponse对象,StreamingHttpResponse对象用于将文件流发送给浏览器,与HttpResponse对象非常相似,对于文件下载功能,使用StreamingHttpResponse对象更合理。
链接:https://www.jianshu.com/p/ce8c17b4a7fd

def download(request):
    try:
        filename = request.GET.get('data',None)
        def file_iterator(file_name):
            with open(file_name, 'rb')as f:
                while True:
                    c = f.read(512)
                    if c:
                        yield c
                    else:
                        break
        response = StreamingHttpResponse(file_iterator(filename))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment;filename={0}".format(filename.split('/')[2])#这里改成自己需要的文件名
        return response
    except Exception as e:
        print (e)

 

下面再 添加一个导入的函数

    def read_excel(request):
        if request.method == 'POST':
            try:
                img = request.FILES.get('file',None)#获得用户上传的excel
                oldName = img.name
                if str(oldName.split(".")[1]) == 'xlsx':#判断格式
                    filename = str(int(time.time() * 10)) + "." + oldName.split(".")[1]
                    dirpath = os.path.join(r'static/excel/',filename)
                    with open(dirpath,'wb+') as destination:
                        for chunk in img.chunks():
                            destination.write(chunk)
                    xlsfile =dirpath  # 打开指定路径中的xlsx文件(读取excel的内容)
                    book = xlrd.open_workbook(xlsfile)  # 得到Excel文件的book对象,实例化对象
                    sheet0 = book.sheet_by_index(0)  # 通过sheet索引获得sheet对象
                    col_data1 = sheet0.col_values(0) #获得第一列的数据
                    col_data = sheet0.col_values(-1)  # 获得最后1列的数据列表
                    return JsonResponse({'code':0})
                else:
                    return JsonResponse({'code':2,'data':'请导入正确格式的表格!'})
            except Exception as e:
                print (e)

导入的前台代码

<label for="exampleInputFile"></label>
<input id='img' type="file" name="file"/>
<button style="border: 1px solid black;width: 60px;height: 30px;margin-top:30px;margin-left:30px;text-align: center;line-height: 15px;background:#c0c0c0;" onclick="FileUpload()">导入</button>
function FileUpload() {
        var form_data = new FormData();
        var file_info = $('#img')[0].files[0];
        form_data.append('file',file_info);
        if(file_info===''){
            alert('你没有选择任何文件');
            return false;
        }
        $.ajax({
            url:"{% url 'read_excel' %}",
            type:'POST',
            data: form_data,
            processData: false,
            contentType: false,
            success: function(j) {
                if (j.code === 0){
                    alert('导入成功!');
                    window.location.reload()
                }else{
                    alert(j.data);
                    window.location.reload()
                }
            }
        });
    }

最后

以上就是搞怪雨为你收集整理的django 一键生成excel表格并下载到本地,并根据时间删除文件,上传excel文件的全部内容,希望文章能够帮你解决django 一键生成excel表格并下载到本地,并根据时间删除文件,上传excel文件所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部