python导入主子表excel数据

python导入主子表excel数据,第1张

# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError
import xlrd, base64, datetime
from xlrd import open_workbook, xldate_as_tuple
import logging

_logger = logging.getLogger(__name__)


def get_cell_value(sCell, ctype):
    '''
    获取Excel日期格式单元格数据,Python读Excel,返回的单元格内容的类型有5种:
    ctype:
    0 :empty
    1: string
    2: number;
    3: date;
    4:boolean,;
    5:error
    :param sCell: 单元格数据
    :param ctype: 数据类型
    :return:
    '''
    # 44197.0 为2021-01-01对应的excel格式的float值,做辅助用
    y_date = 44197.0
    istime = 0
    # 日期格式
    if ctype == 3:
        if sCell < 1:
            istime = 1
            sCell = y_date + sCell
        dtime = datetime.datetime(*xldate_as_tuple(sCell, 0))
        strTime = dtime.strftime('%Y-%m-%d')
        # 只包含时间,没有日期 比如:01:31:52
        if istime == 1:
            return strTime[11:]
        else:
            return strTime
    else:
        return sCell


def check_id_data(n):
    """
    校验身份证是否正确
    """
    if len(str(n)) != 18:
        print("身份证号为[%s],核验失败" % n)
        return 0
    var = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    var_id = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2']
    n = str(n)
    sum = 0
    if int(n[16]) % 2 == 0:
        gender = "女"
        same = int(int(n[16]) / 2)
    else:
        gender = "男"
        same = int((int(n[16]) + 1) / 2)
    for i in range(0, 17):
        sum += int(n[i]) * var[i]
    sum %= 11
    if (var_id[sum]) != str(n[17]):
        print("身份证号为[%s],核验失败" % n)
        return 0
    else:
        return 1


class TalentInfoWizard(models.TransientModel):
    _name = 'import.talent.info.wizard'
    _description = '人才信息'

    data = fields.Binary(u'请选择文件')

    def btn_confirm(self):
        """
           有模板可以下载,按照模板整理数据导入
          用xlrd 解析excel中单数据,导入系统模块中
          注意点:1、专业要求:此字段是many2many的,
                   excel里面的数据是用逗号隔开的;
                2、分别获取excel数据,保存在字典里
                  base_infos 是基础数据部分;
                  projects 是项目信息部分;
        """
        for_obj = self.env['talent.information'].sudo()
        res_id = self.env.context.get('res_id')
        old_records = for_obj.search([('talent_work_center_id', '=', res_id), ('by_import', '=', True)])
        old_records.sudo().unlink()
        excel_obj = xlrd.open_workbook(file_contents=base64.decodebytes(self.data))
        sheets = excel_obj.sheets()
        base_infos = self.get_baseinfo_data(sheets[0])
        data_type = type(base_infos)
        print(data_type)
        print('-----base_infos--------', base_infos)
        if isinstance(data_type, str) == True:
            print('999999999')
            notification = {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': u'数据校验',
                    'message': base_infos,
                    'sticky': True,
                    'type': 'warning',
                    'next': {
                        'type': 'ir.actions.act_window_close'
                    },
                },
            }
            return notification
        projects = self.get_project_data(sheets[1])
        for item in base_infos:
            # 创建信息主表
            main_id = for_obj.create(item)
            eff_values = list(filter(lambda x: x['id_number'] == item['ID_number'], projects))
            pro_list = []
            for line in eff_values:
                pro_list.append(
                    (0, 0, {'name': line['name'], 'code': line['code'], 'description': line['description']}))
            main_id.write({'talent_project_info_ids': pro_list})
        notification = {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': u'数据校验',
                'message': '数据导入成功',
                'sticky': False,
                'type': 'success',
                'next': {
                    'type': 'ir.actions.act_window_close'
                },
            },
        }
        return notification

    def get_baseinfo_data(self, sh):
        """获取基本信息"""
        err_msg = []
        res_id = self.env.context.get('res_id')
        plan_obj = self.env['talent.information.plan'].sudo()
        state_obj = self.env['res.country.state'].sudo()
        country_obj = self.env['res.country'].sudo()
        nation_obj = self.env['base.nation'].sudo()
        pro_obj = self.env['talent.professional'].sudo()
        area_obj = self.env['talent.professional.area'].sudo()
        title_obj = self.env['talent.title'].sudo()
        comp_obj = self.env['res.company'].sudo()
        # 主表ID talent_work_center_id
        values_line = []
        for row in range(1, sh.nrows):
            name = sh.cell(row, 0).value
            gender = sh.cell(row, 1).value
            age = sh.cell(row, 2).value
            date_birthday = sh.cell(row, 3).value
            # m2o nation
            base_nation = sh.cell(row, 4).value
            nation_id = False
            if base_nation:
                nation = nation_obj.search([('name', '=', base_nation)])
                if nation:
                    nation_id = nation.id
            # todo country
            country_id = False
            country_name = sh.cell(row, 5).value
            if country_name:
                country = country_obj.search([('name', '=', country_name)])
                if country:
                    country_id = country.id

            # todo state
            state_id = False
            res_country_state = sh.cell(row, 6).value
            if res_country_state:
                country_state = state_obj.search([('name', '=', res_country_state)])
                if country_state:
                    state_id = country_state.id
            certificates_type = sh.cell(row, 7).value
            ID_number = sh.cell(row, 8).value
            if certificates_type == '身份证' and ID_number:
                result = check_id_data(ID_number)
                if result == 0:
                    err_msg.append(ID_number)
            company_type_str = sh.cell(row, 9).value
            company_name = sh.cell(row, 10).value
            company_type_id = False
            company_id = False
            if company_type_str:
                company_type = comp_obj.search([('name', '=', company_type_str)])
                if company_type:
                    company_type_id = company_type.id
            if company_name:
                company_str_name = comp_obj.search([('name', '=', company_name)])
                if company_str_name:
                    company_id = company_str_name.id
            participate_time = sh.cell(row, 11).value
            join_company_time = sh.cell(row, 12).value
            pol_outlook = sh.cell(row, 13).value
            education = sh.cell(row, 14).value
            graduation_school = sh.cell(row, 15).value
            major_studied = sh.cell(row, 16).value
            job_education = sh.cell(row, 17).value
            degree_education = sh.cell(row, 18).value
            job_graduation_school = sh.cell(row, 19).value
            talent_professional = sh.cell(row, 20).value
            talent_professional_id = False
            if talent_professional:
                if talent_professional:
                    talent_pro_name = pro_obj.search([('name', '=', talent_professional)], limit=1)
                    if talent_pro_name:
                        talent_professional_id = talent_pro_name.id

            talent_skill_job_id = sh.cell(row, 21).value

            # todo m2o
            # PJ = sh.cell(row, 22).value
            # pro_list = []
            # if PJ:
            #     for line in PJ.split(','):
            #         pro_id = project_obj.search([('code', '=', line)], limit=1)
            #         # 如果没有查到则退出当前循环,进到下一循环
            #         pro_list.append((0, 0, {'talent_project_id': pro_id.id}))

            area_str = sh.cell(row, 23).value
            area_id = False
            if area_str:
                area_name = area_obj.search([('name', '=', area_str)], limit=1)
                if area_name:
                    area_id = area_name.id
            job_name = sh.cell(row, 24).value
            rank_level = sh.cell(row, 25).value
            other_professional = sh.cell(row, 26).value
            specific_specialty = sh.cell(row, 27).value
            talent_title = sh.cell(row, 28).value
            title_id = False
            if talent_title:
                talent_name = title_obj.search([('name', '=', talent_title)], limit=1)
                if talent_name:
                    title_id = talent_name.id
            # m2o
            talent_plan_str = sh.cell(row, 29).value
            plan_list = []
            if talent_plan_str:
                for plan_str in talent_plan_str.split(','):
                    plan_id = plan_obj.search([('name', '=', plan_str)], limit=1).id or False
                    # 如果没有查到则退出当前循环,进到下一循环
                    if plan_id:
                        plan_list.append(plan_id)
            talent_level = sh.cell(row, 30).value
            talent_echelon_level = sh.cell(row, 31).value
            values_line.append({
                'talent_work_center_id': res_id,
                'name': name,
                'gender': gender,
                'country_id': country_id,
                'company_type': company_type_id,
                'talent_skill_job_id': talent_skill_job_id,
                'company_id': company_id,
                'res_country_state': state_id,
                'talent_plan_ids': [(6, 0, plan_list)],
                # 'talent_project_info_ids': pro_list,
                'age': age,
                'date_birthday': get_cell_value(date_birthday, 3),
                'certificates_type': certificates_type,
                'ID_number': ID_number,
                'participate_time': get_cell_value(participate_time, 3),
                'join_company_time': get_cell_value(join_company_time, 3),
                'base_nation': nation_id,
                'pol_outlook': pol_outlook,
                'education': education,
                'graduation_school': graduation_school,
                'major_studied': major_studied,
                'job_education': job_education,
                'degree_education': degree_education,
                'job_graduation_school': job_graduation_school,
                'talent_professional_id': talent_professional_id,
                'professional_area': area_id,
                'job_name': job_name,
                'rank_level': rank_level,
                'other_professional': other_professional,
                'specific_specialty': specific_specialty,
                'talent_title': title_id,
                'talent_level': talent_level,
                'talent_echelon_level': talent_echelon_level,
                'by_import': True
            })

        if err_msg:
            message = '数据校验失败,下列身份证号无效【%s】' % ','.join(err_msg)
            return message
        return values_line

    def get_project_data(self, sh):
        """获取项目表信息"""
        result = []
        for row in range(1, sh.nrows):
            item = {
                'id_number': sh.cell(row, 0).value or '',
                'code': sh.cell(row, 1).value or '',
                'name': sh.cell(row, 2).value or '',
                'description': sh.cell(row, 3).value or '',
            }
            result.append(item)
        return result

验证身份z号:

def check_id_length(n):
    if len(str(n)) != 18:
        print("只支持18位身份z号查询")
        return False
    else:
        return True
        
        
        
def check_id_data(n):
        var=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
        var_id=['1','0','x','9','8','7','6','5','4','3','2']
        n = str(n)
        sum = 0
        if int(n[16])%2==0:
            gender="女"
            same=int(int(n[16])/2)
        else:
            gender="男"
            same=int((int(n[16])+1)/2)
        for i in range(0,17):
            sum += int(n[i])*var[i]
        sum %= 11
        if (var_id[sum])==str(n[17]):
            print("身份z号规则核验通过,校验码是:",var_id[sum])
            print("出生于:",n[6:10],"年",n[10:12],"月",n[12:14],"日","性别:",gender,"\n当地同性别同生日排名:",same)
            return sum
        else:
            print("出生于:",n[6:10],"年",n[10:12],"月",n[12:14],"日","性别:",gender,"\n当地同性别同生日排名:",same)
            print("但身份z号规则核验失败,校验码应为",var_id[sum],",当前校验码是:",n[17])
            return 0
n = input("请输入18位身份z号:")
if check_id_length(n):
    check_id_data(n)
else:
    print("请重新输入")
                                                                                        中亿丰——何双新

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/714183.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存