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
| def xlsx_excel(headers, results, filename): excel_stream = io.BytesIO() workbook = xlsxwriter.Workbook(excel_stream) worksheet = workbook.add_worksheet() header_format = workbook.add_format({ 'num_format': '@', }) data_validate = {'validate': 'list', 'source': ['是', '否']} data_validate1 = {'validate': 'list', 'source': ['有', '无']} date_validate = {'validate': 'date', 'criteria': 'between', 'minimum': date(2018, 1, 1), 'maximum': date(9999, 12, 12)} for i in range(len(headers)): if isinstance(headers[i], tuple): if "自动计算" in headers[i][0]: worksheet.write(0, i, headers[i][0]) worksheet.write_formula(1, i, headers[i][1], header_format) elif "text" in headers[i][1]: r = headers[i][1].replace('text', '') worksheet.write(0, i, headers[i][0], workbook.add_format({'font_color': 'red'})) worksheet.set_column("{}:{}".format(r, r), None, header_format) elif "date" in headers[i][1]: r = headers[i][1].replace('date', '') worksheet.write(0, i, headers[i][0], workbook.add_format({'font_color': 'red'})) worksheet.data_validation('{}2:{}1048576'.format(r, r), date_validate) else: worksheet.write(0, i, headers[i][0], workbook.add_format({'font_color': 'red'})) worksheet.data_validation('{}2:{}1048576'.format(headers[i][1], headers[i][1]), data_validate) else: worksheet.write(0, i, headers[i], workbook.add_format({'font_color': 'red'})) for x in range(len(results)): worksheet.write_row("A{}".format(x + 2), results[x]) workbook.close() xlsx_data = excel_stream.getvalue() response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % filename response.write(xlsx_data) return response
headers = [("日期", 'dateA'), "姓名", ("手机号", "textC"), "数字一", "数字二", ("合计(自动计算)", "=D2+E2")] results = [["2019/1/1", "张三", "18888888888", "1000", 1000]] filename = "test_excel" xlsx_excel(headers, results, filename)
|