自定義Excel匯出功能
阿新 • • 發佈:2019-01-02
例:
def export_data_to_excel(conf, header_only=False, filter_dict=None, plus_sites=False): from django.http import HttpResponse import xlwt date_style = xlwt.XFStyle() date_style.num_format_str = 'yyyy-mm-dd' def check_conf(c): obj = get_class(c) for field_name in c["attributes"].keys(): if not hasattr(obj, field_name): print "{} has no attr '{}', please check.".format(c["class_name"], field_name) return False return True def write_head(c, s): header = c.get("header", []) for h in range(len(header)): s.write(0, h, header[h]) if plus_sites: from excel_export_conf import SiteExportConfig for site_col, name in SiteExportConfig: s.write(0, site_col, name) if not check_conf(conf): return HttpResponse(STRING_IMPORT_CONFIGURATION_ERROR) if not filter_dict: filter_dict = {} excel = xlwt.Workbook(encoding='utf8') sheet = excel.add_sheet(conf.get("sheet_name", "sheet")) write_head(conf, sheet) if not header_only: if type(filter_dict) == django.db.models.query_utils.Q: objects = get_class(conf).objects.filter(filter_dict) else: objects = get_class(conf).objects.filter(**filter_dict) len_d = len(objects) for i in range(1, len_d+1): s_data = objects[i - 1] for k, v in conf["attributes"].items(): field = s_data._meta.get_field(k) choices = field.__dict__["choices"] if choices: for key, value in choices: if key == s_data.__getattribute__(k): sheet.write(i, v, value) elif type(field) == DateField: sheet.write(i, v, s_data.__getattribute__(k), date_style) else: sheet.write(i, v, s_data.__getattribute__(k)) if plus_sites: from excel_export_conf import SiteExportConfig from Release.models import ReleaseItemWithSite for site_col, name in SiteExportConfig: site_value = get_site_choices(name) if site_value: sites = ReleaseItemWithSite.objects.filter(site_name=site_value, product_id=s_data.id) if sites: sheet.write(i, site_col, sites[0].contract_end_date, date_style) response = HttpResponse(content_type='application/msexcel') response['Content-Disposition'] = 'attachment; filename=%s.xls'%conf.get("excel_name", "excel") excel.save(response) return response
FinanceBuyAndSoldRecord = { "module_name": "Finance.models", "class_name": "FinanceBuyAndSoldRecord", "excel_name": "投入產出比", "sheet_name": "投入產出比", "header": ["片單型別", "採購合同編號", "合作單位(買)", "採購片單名稱", "採購合同金額", "集數", "單價", "授權開始日期", "授權截止日期", "銷售合同編號", "合作單位(賣)", "銷售合同金額", "集數", "單價", "授權開始日期", "授權截止日期", ], "attributes": { "type": 0, # 型別 "buy_contract_id": 1, # 採購合同編號 "buy_company": 2, # 合作單位(買) "name": 3, # 採購片單名稱 "buy_price": 4, # 採購合同金額 "buy_series": 5, # 集數 "buy_unit_price": 6, # 單價 "buy_authorized_date_start": 7, # 授權開始日期 "buy_authorized_date_end": 8, # 授權截止日期 "sold_contract_id": 9, # 銷售合同編號 "sold_company": 10, # 合作單位(賣) "sold_price": 11, # 銷售合同金額 "sold_series": 12, # 集數 "sold_unit_price": 13, # 單價 "sold_authorized_date_start": 14, # 授權開始日期 "sold_authorized_date_end": 15, # 授權截止日期 }, }
# 匯出投入產出比 def input_output_export_static(request): try: params = request.POST if request.method == 'POST' else request.GET filters = get_input_output_filters(params) return export_data_to_excel(FinanceBuyAndSoldRecord, header_only=False, filter_dict=filters) except Exception as e: return render(request, 'error.html', locals())