python通过xlwt模块直接在网页上生成excel文件并下载

urls:

from django.conf.urls import url, include
from . import views

urlpatterns = [
...
    url(r'^domains/_export_dns.html', views.export_dns, name='export_dns'),
...
]

 

view:

import xlrd, xlwt

def set_style(name, height, bold=False):
    """
    excel样式
    :param name: 字体名
    :param height: 调度
    :param bold: 边框
    :return:
    """
    style = xlwt.XFStyle()  # 初始化样式
    font = xlwt.Font()  # 为样式创建字体
    font.name = name  # 'Times New Roman'
    font.bold = bold
    font.color_index = 000
    font.height = height
    style.font = font

    # 设置单元格边框
    # borders= xlwt.Borders()
    # borders.left= 6
    # borders.right= 6
    # borders.top= 6
    # borders.bottom= 6
    # style.borders = borders

    # 设置单元格背景颜色
    # pattern = xlwt.Pattern()
    # 设置其模式为实型
    # pattern.pattern = pattern.SOLID_PATTERN
    # 设置单元格背景颜色
    # pattern.pattern_fore_colour = 0x00
    # style.pattern = pattern

    return style

@login_required
def export_dns(req):
    """
    导出DNS解析记录
    :param req:
    :return:
    """

    if req.method == 'GET':
        data = req.GET.get('data')
        data = json.loads(data)

        zone_tag_obj = models.ZoneTag.objects.get(zone_name=data['zone'])
        record_obj_list = zone_tag_obj.ZoneTag_Record.filter( ~Q(type='SOA') )

        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="%s.xls"' %(data['zone'])

        book = xlwt.Workbook(encoding='utf-8')
        sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)
        row0 = ['主机记录', '记录类型', '解析线路', '记录值', 'MX优先级', 'TTL', '状态', '备注']
        # 设置列宽
        sheet.col(0).width = 6000
        sheet.col(1).width = 3000
        sheet.col(2).width = 3000
        sheet.col(3).width = 6000
        sheet.col(4).width = 3000
        sheet.col(5).width = 3000
        sheet.col(6).width = 3000
        sheet.col(7).width = 12000
        for i in range(0, len(row0)):
            sheet.write_merge(0, 0, i, i, row0[i], set_style('Times New Roman', 220, True))

        for k, v in enumerate(record_obj_list, start=1):
            sheet.write(k, 0, v.host)
            sheet.write(k, 1, v.type )
            sheet.write(k, 2, v.resolution_line )
            sheet.write(k, 3, v.data )
            sheet.write(k, 4, v.mx_priority )
            sheet.write(k, 5, v.ttl)
            sheet.write(k, 6, v.status)
            sheet.write(k, 7, v.comment )

        book.save(response)

        return response
    elif req.method == 'POST':
        msg = {'status': 200}
        return HttpResponse(json.dumps(msg))

 

 

js:

function ExportDnsRecordACK(){
    // 确认导出DNS解析记录
    var _export_dns_record_type = $("select[name=export_dns_record_type]")[0].value.trim();
    var _zone = $("#ExportDnsRecordModalLabel h4").attr('domain')
    var __data = {'data': _export_dns_record_type, 'zone':_zone}

    var url = "/domains/_export_dns.html?data=" + JSON.stringify(__data);

    $.ajax({
        url: "/domains/_export_dns.html",
        type: "POST",        //请求类型
        data: {},
        //async : false,
        dataType: "json",
        //beforeSend:function(XMLHttpRequest){
        //    // 请求前执行
        //},
        success: function (response, status, request) {
            //当向服务端发起的请求执行成功完成后,自动调用
            if(request['status'] == 200){
                $('#ExportDnsRecordModalLabel').modal('hide');
                window.location.href = url;     //下载文件
            }
        },
        error: function () {
            //当请求错误之后,自动调用
        }
    });
}


$(document).ready(function(){
    // 确认 导出DNS解析记录
    $(document).on("click", 'button[name=_export_dns_record_ok]', ExportDnsRecordACK);
}

 

转载于:https://www.cnblogs.com/linkenpark/p/9623566.html

你可能感兴趣的:(python通过xlwt模块直接在网页上生成excel文件并下载)