#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Date:2022/07/25 14:57:23 ''' import time import json import uuid import datetime from string import ascii_uppercase from openpyxl import load_workbook class ReadExcel: def __init__(self, excelName): self.wb = load_workbook(filename=excelName) self.ws = self.wb.active self.template_list = [] def read(self, func_type): max_lines = self.ws.max_row if self.ws['C1'].value == 'template_content': for key in range(2, max_lines + 1): value = self.ws['{}'.format('C' + str(key))].value self.template_list.append(value) return self.template_list elif self.ws['A1'].value == '单位编号' and self.ws['B1'].value == '产品编号': drug_list = [] # lineIndex = 0 try: for line in range(2, max_lines + 1): # 局部方法,传递字符和默认值返回方法调用,简化代码量 value_func = lambda x, y='': str( self.ws[f"{x}{line}"].value or y) # 声明一个字典存放每一行的数据 每遍历一次字典重置一次 drug_template_dict = { "variety_id": str(uuid.uuid1()), } # TODO 添加供应商修改 key_list = [ "unit_code", "remark2", "category", "speci", "name", "english_name", "purity", "cas_number", "standard_code", "net_weight", "net_weight_unit", "export_count", "production_date", "shelf_life", "expiration_date", "price", "is_supervise", "remain", "manufacturer", "distributor", "storage_condition", "remark9" ] v_list = list("ABCDEFGHIJKLNOPQRSTUVW") # 采用列表和字母对应的两个列表,进行循环的方式写入字典,简化代码量 str_tim = "%Y-%m-%d %H:%M:%S" def date_func(x): return datetime.datetime.strptime( x, str_tim) for i in range(len(key_list)): v_key = v_list[i] key_key = key_list[i] # 时间格式转换 if key_key == "production_date" or key_key == "expiration_date": # 计算保质期 va = value_func(v_key) if va: if len(va) > 0 and len(va) == 10: va += " 00:00:00" else: va = date_func(va).strftime(str_tim) if key_key == "production_date": if va: value = va else: value = time.strftime(str_tim[:8]) + " 00:00:00" elif key_key == "expiration_date": if va: value = va else: value = ( date_func(drug_template_dict.get("production_date")) + datetime.timedelta(days=360) ).strftime(str_tim) elif key_key == "is_supervise": va = value_func(v_key) if va == "否": value = 0 else: value = 1 else: value = value_func(v_key) drug_template_dict[key_list[i]] = value if key_list[i] == "name" and drug_template_dict.get("name") == "": self.template_list.append(json.dumps(drug_list)) return self.template_list # 计算保质期 shelf_life = drug_template_dict.get("shelf_life") if not shelf_life: shelf_life = ( date_func(drug_template_dict.get("expiration_date")) - date_func(drug_template_dict.get("production_date"))).days drug_template_dict["shelf_life"] = shelf_life drug_template_dict["func_type"] = func_type drug_template_dict["total"] = drug_template_dict.get("remain") drug_list.append(drug_template_dict) self.template_list.append(json.dumps(drug_list)) return self.template_list except Exception as e: raise RuntimeError('第{0}行;{1}'.format(str(line), str(e))) else: raise RuntimeError('模板格式错误!') def close(self): self.wb.close() def time_long(self, time1, time2, type="day"): """ 计算时间差 :param time1: 较小的时间(datetime类型) :param time2: 较大的时间(datetime类型) :param type: 返回结果的时间类型(暂时就是返回相差天数) :return: 相差的天数 """ def da(x): return time.strptime(str(x), '%Y-%m-%d %H:%M:%S') if type == 'day': day_num = (int(time.mktime(da(time2))) - int(time.mktime(da(time1)))) / ( 24 * 60 * 60) return abs(int(day_num))