python导出excel简单模版

from io import BytesIO

from django.http import HttpResponse
import xlwt


FILE_NAME = '导出excel'
EXPORT_FIELDS_DICT = {
    "名字": "name",
    "编号": "code",
    "年龄": "age",
    "性别": "hex"
}


def export(self, export_filed_dict, data, file_name):
    response = HttpResponse(content_type='application/vnd.ms-excel')
    filename = file_name
    response['Content-Disposition'] = u'attachment;filename= ' + filename.encode('gbk').decode(
        'ISO-8859-1') + '.xls'
    # 创建一个文件对象
    wb = xlwt.Workbook(encoding='utf8')
    # 创建一个sheet对象
    sheet = wb.add_sheet(file_name, cell_overwrite_ok=True)
    style = xlwt.XFStyle()
    style.alignment.wrap = 1

    # 写入文件标题
    for col_num in range(len(export_filed_dict)):
        sheet.write(0, col_num, list(export_filed_dict.keys())[col_num])
        # 写入数据
        data_row = 1
        for i in data:
            if not i.get('equip_component_name'):
                i.update({'equip_component_name': None})
            sheet.write(data_row, col_num, i[list(export_filed_dict.values())[col_num]])
            data_row += 1

    # 写出到IO
    output = BytesIO()
    wb.save(output)
    # 重新定位到开始
    output.seek(0)
    response.write(output.getvalue())
    return response

 

posted @ 2022-04-27 15:33  死里学  阅读(506)  评论(0)    收藏  举报