django导出数据生成excel并下载到本地

功能分析:
1、生成excel文件;
2、将生成的excel文件下载到本地;

utils.py文件中完成excel文件的数据写入,及生成表格样式设置

import xlwt,datetime
from xlwt import *
# 写入excel文件函数
def wite_to_excel(n,head_data,records,download_url):
    #获取时间戳
    timestr = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

    # 工作表
    wbk = xlwt.Workbook()
    sheet1 = wbk.add_sheet('sheet1',cell_overwrite_ok=True)

    #写入表头
    for filed in range(0,len(head_data)):
        sheet1.write(0,filed,head_data[filed],excel_head_style())


    #写入数据记录
    for row in range(1,n+1):
        for col in range(0,len(head_data)):
            sheet1.write(row,col,records[row-1][col],excel_record_style())
            #设置默认单元格宽度
            sheet1.col(col).width = 256*15

    wbk.save(download_url+'New-'+timestr+'.xls')
    return timestr

# 定义导出文件表头格式
def excel_head_style():
    # 创建一个样式
    style = XFStyle()
    #设置背景色
    pattern = Pattern()
    pattern.pattern = Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = Style.colour_map['light_green']  # 设置单元格背景色
    style.pattern = pattern
    # 设置字体
    font0 = xlwt.Font()
    font0.name = u'微软雅黑'
    font0.bold = True
    font0.colour_index = 0
    font0.height = 240
    style.font = font0
    #设置文字位置
    alignment = xlwt.Alignment()  # 设置字体在单元格的位置
    alignment.horz = xlwt.Alignment.HORZ_CENTER  # 水平方向
    alignment.vert = xlwt.Alignment.VERT_CENTER  # 竖直方向
    style.alignment = alignment
    # 设置边框
    borders = xlwt.Borders()  # Create borders
    borders.left = xlwt.Borders.THIN  # 添加边框-虚线边框
    borders.right = xlwt.Borders.THIN  # 添加边框-虚线边框
    borders.top = xlwt.Borders.THIN  # 添加边框-虚线边框
    borders.bottom = xlwt.Borders.THIN  # 添加边框-虚线边框
    style.borders = borders

    return style

# 定义导出文件记录格式
def excel_record_style():
    # 创建一个样式
    style = XFStyle()
    #设置字体
    font0 = xlwt.Font()
    font0.name = u'微软雅黑'
    font0.bold = False
    font0.colour_index = 0
    font0.height = 200
    style.font = font0
    #设置文字位置
    alignment = xlwt.Alignment()  # 设置字体在单元格的位置
    alignment.horz = xlwt.Alignment.HORZ_CENTER  # 水平方向
    alignment.vert = xlwt.Alignment.VERT_CENTER  # 竖直方向
    style.alignment = alignment
    # 设置边框
    borders = xlwt.Borders()  # Create borders
    borders.left = xlwt.Borders.THIN  # 添加边框-虚线边框
    borders.right = xlwt.Borders.THIN  # 添加边框-虚线边框
    borders.top = xlwt.Borders.THIN  # 添加边框-虚线边框
    borders.bottom = xlwt.Borders.THIN  # 添加边框-虚线边框
    style.borders = borders

    return style

views.py文件调用上述函数完成excel文件的生成

import os,sys
from public.utils import *

#导出功能实现
def process_export_excel(request):
    project_codes = request.POST.get("project_code")
    project_codes = project_codes.split(',')
    n = len(project_codes)

    #表头字段
    head_data = [u'项目编号',u'项目名称',u'测试阶段',u'测试周期',u'提测日期',u'上线日期',u'研发负责人',u'测试负责人',u'进度',u'进度是否正常',u'影响进度原因',u'冒烟测试是否通过',u'冒烟测试未通过原因',u'备注']
    #查询记录数据
    records = []
    for project_code in project_codes:
        if project_code != "":
            project_obj = Project.objects.get(project_code=project_code)
            project_code = project_obj.project_code
            project_name = project_obj.project_name
            project_developer = project_obj.developer
            project_tester = project_obj.tester
            project_test_days = project_obj.test_days
            project_test_start_date = project_obj.test_start_date
            project_release_date = project_obj.release_date

            process_obj = Process.objects.get(project_code=project_code)
            process_stage = process_obj.get_process_stage_display()
            process_percent = process_obj.process_percent
            process_is_percent_nomal = process_obj.get_is_percent_nomal_display()
            process_unnomal_reason = process_obj.unnomal_reason
            is_pass_smoketest = process_obj.get_is_pass_smoketest_display()
            nopass_smoketest_reason = process_obj.nopass_smoketest_reason

            daiyRecord_obj = DailyRecord.objects.filter(project_code_id=project_code).values()
            daiyRecord_list = list(daiyRecord_obj)
            problem_record= daiyRecord_list[-1]['problem_record']

            record = []
            record.append(project_code)
            record.append(project_name)
            record.append(process_stage)
            record.append(project_test_days)
            record.append(str(project_test_start_date)[0:10])
            record.append(str(project_release_date)[0:10])
            record.append(project_developer)
            record.append(project_tester)
            record.append(process_percent+'%')
            record.append(process_is_percent_nomal)
            record.append(process_unnomal_reason)
            record.append(is_pass_smoketest)
            record.append(nopass_smoketest_reason)
            record.append(problem_record)

        records.append(record)

    #获取当前路径
    cur_path = os.path.abspath('.')
    #设置生成文件所在路径
    download_url = cur_path+'\\upload\\'

    #写入数据到excel中
    ret = wite_to_excel(n,head_data,records,download_url)

    return HttpResponse(ret)

下载功能实现

view.py添加download函数

def download(request,offset):

    from django.http import StreamingHttpResponse
    def file_iterator(file_name,chunk_size=512):
        with open(file_name,'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    # 显示在弹出对话框中的默认的下载文件名
    the_file_name ='New-'+offset+'.xls'

    #获取当前路径
    cur_path = os.path.abspath('.')
    #设置生成文件所在路径
    download_url = cur_path+'\\upload\\'

    response = StreamingHttpResponse(file_iterator(download_url+'New-'+offset+'.xls'))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)

    return response

html文件中选择导出数据并下载

        
        

js

        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        function csrfSafeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        //导出
        function downData() {
            var env_codes = new Array();
            var count = 0;
            var i = 0;
            $("#myAlert").css("display", "none");
            $("#myAlert1").css("display", "none");
            $("#myAlert2").css("display", "none");
            $("#table").find(":checkbox:checked").each(function () {
                env_code = $(this).parent().next().text();
                //alert(env_code);
                if (env_code != "") {
                    env_codes[i++] = env_code;
                }
                count++;
            });
            if (count == 0) {
                $("#myAlert2").css("display", "inherit");
                return false;
            }
            $("#downData").val(env_codes)
            var project_code = $("#downData").val()
            //alert(project_code);
            $.ajax({
                type: 'POST',
                url: '/project/process/process_export_excel/',
                dataType: 'text',
                data: {'project_code': project_code},
                beforeSend: function (xhr, settings) {
                    var csrftoken = getCookie('csrftoken');
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                },
                success: function (text) {
                    var url = '/project/process/download/' + text;
                    window.location.href = url;
                },
                error: function () {
                    alert('导出失败');
                }
            });

        }

urls.py文件路由配置

    url('^/process_export_excel/$', proviews.process_export_excel),
    url('^/download/(\w+)*/$', proviews.download),

你可能感兴趣的:(django导出数据生成excel并下载到本地)