1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| import xlsxwriter from django.http import StreamingHttpResponse, JsonResponse, FileResponse from django.http import HttpResponse from django.urls import reverse_lazy from django.utils.encoding import escape_uri_path
def export_data(request): filename = '{}.xlsx'.format('人员信息') if request.method == 'GET': try: response = StreamingHttpResponse(file_iterator(filename)) response['Content-Type'] = 'application/octet-stream' response["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(escape_uri_path(filename)) except: return HttpResponse("生成文件失败") return response
if request.method == 'POST': ping_header = { '姓名': '1', '性别': '2', '年龄': '3', '居住地址': '4', } data = [ {'name': '刘备', 'sex': '男', 'age': 18, 'addr': '荆州'}, {'name': '关羽', 'sex': '女', 'age': 10, 'addr': '荆州'}, {'name': '张飞', 'sex': '男', 'age': 10, 'addr': '荆州'}, {'name': '黄宇恒', 'sex': '其他', 'age': 99, 'addr': '江西省南昌市进贤县'}, ] workbook = xlsxwriter.Workbook(filename) worksheet = workbook.add_worksheet("人员信息统计") head_style = workbook.add_format(xlsx_style(bold=True, bg_color='#95B3D7')) body_style = workbook.add_format(xlsx_style()) _header = ping_header for index, value in enumerate(_header): worksheet.write(0, index + 4, value, head_style) n_index = 1 if len(data) > 0: for item in data: worksheet.write(n_index, 4, item['name'] if item.get('name') else '', body_style) worksheet.write(n_index, 5, item['sex'] if item.get('sex') else '', body_style) worksheet.write(n_index, 6, item['age'] if item.get('age') else '', body_style) worksheet.write(n_index, 7, item['addr'] if item.get('addr') else '', body_style)
n_index += 1
workbook.close() url = reverse_lazy('app_name:路由名称') return JsonResponse({'redirect': url, 'code': 0})
def file_iterator(file_path, chunk_size=512): """ 文件生成器,防止文件过大,导致内存溢出 :param file_path: 文件路径 :param chunk_size: 块大小 :return: 生成器 """ with open(file_path, mode='rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break
def xlsx_style(**kwargs): style = { 'bold': kwargs.get('bold', False), 'font_name': kwargs.get('font_name', 'SimSun'), 'font_size': kwargs.get('font_size', 10), 'font_color': kwargs.get('font_color', '#000000'), 'align': kwargs.get('align', 'center'), 'valign': kwargs.get('valign', 'vcenter'), 'text_wrap': kwargs.get('text_wrap', True), 'top': kwargs.get('top', 1), 'bottom': kwargs.get('bottom', 1), 'left': kwargs.get('left', 1), 'right': kwargs.get('right', 1), 'bg_color': kwargs.get('bg_color', '#FFFFFF'), } return style
|