当前位置 博文首页 > python生成word合同的实例方法

    python生成word合同的实例方法

    作者:十一 时间:2021-02-10 18:30

    在企业招聘中,最重要的事情,就是需要签订劳动合同,但是有些大的公司,因为人员过于,在设置编辑合同的时候,比较耗时耗力,编程存在的意义,就是帮助我们实现办公自动化,因此能实现自动生成合同,还是非常重要的,下面小编就来采用函数以及面向对象过程,教大家实现生成合同过程。

    1、模板文件

    甲方公司、乙方人员姓名、乙方部门、乙方职位、甲方人员姓名、乙方人员姓名、时间(年月日),如图所示。

    2、实现代码

    from docxtpl import DocxTemplate
    import os
    import pymysql
    import time
    cur_path = os.path.dirname(__file__)
    tempfilename = os.path.join(cur_path, 'template', '劳动合同模板.docx')
    today = time.strftime("%Y-%m-%d", time.localtime())
    def query():
    try:
    # 数据库连接,返回数据库连接对象
    conn = pymysql.connect(host='localhost', user='root',
    passwd='123456', db='test', port=3306)
    cur = conn.cursor()
    sql = 'select * from t_person_info'
    cur.execute(sql)
    result = cur.fetchall()
    return result
    except Exception as e:
    print(e)
    finally:
    conn.close()
    def build_hetong():
    result = query()
    for x in result:
    tpl = DocxTemplate(tempfilename)
    context = {
    'firstparty': '灯塔教育',
    'secondparty': x[1],
    'department': x[15],
    'job': x[16],
    'owner': '龙卷风',
    'name': x[1],
    'sj': today
    }
    tpl.render(context)
    savefilename=os.path.join(cur_path,'build',x[1]+'劳动合同.docx')
    tpl.save(savefilename)
    if __name__ == "__main__":
    start = time.time()
    build_hetong()
    end = time.time()
    sj = end-start
    print(f"花费时间(秒):{sj}")

    3、输出结果

    实例扩展(批量WORD合同生成)

    导入数据库

    #导入对应数据库
    import numpy as np 
    import pandas as pd 
    import os 
    import docx
    from docx.shared import Pt
    from docx.oxml.ns import qn
    #修改项目文件地址
    os.chdir(r'C:\Users\WIN7\Desktop\分期账单自动化')
    os.getcwd()

    全部代码:

    '''
    人民币数字转大写汉字
    '''
    # coding: utf-8
    import warnings
    from decimal import Decimal
    
    def cncurrency(value, capital=True, prefix=False, classical=None):
     '''
     参数:
     capital: True 大写汉字金额
        False 一般汉字金额
     classical: True 元
        False 圆
     prefix:  True 以'人民币'开头
        False, 无开头
     '''
     if not isinstance(value, (Decimal, str, int)):
      msg = '''
      由于浮点数精度问题,请考虑使用字符串,或者 decimal.Decimal 类。
      因使用浮点数造成误差而带来的可能风险和损失作者概不负责。
      '''
      warnings.warn(msg, UserWarning)
     # 默认大写金额用圆,一般汉字金额用元
     if classical is None:
      classical = True if capital else False
      
     # 汉字金额前缀
     if prefix is True:
      prefix = '人民币'
     else:
      prefix = ''
      
     # 汉字金额字符定义
     dunit = ('角', '分')
     if capital:
      num = ('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖')
      iunit = [None, '拾', '佰', '仟', '万', '拾', '佰', '仟','亿', '拾', '佰', '仟', '万', '拾', '佰', '仟']
     else:
      num = ('〇', '一', '二', '三', '四', '五', '六', '七', '八', '九')
      iunit = [None, '十', '百', '千', '万', '十', '百', '千','亿', '十', '百', '千', '万', '十', '百', '千']
     if classical:
      iunit[0] = '元' if classical else '圆'
     # 转换为Decimal,并截断多余小数
    
     if not isinstance(value, Decimal):
      value = Decimal(value).quantize(Decimal('0.01'))
    
     # 处理负数
     if value < 0:
      prefix += '负'   # 输出前缀,加负
      value = - value   # 取正数部分,无须过多考虑正负数舍入
            # assert - value + value == 0
     # 转化为字符串
     s = str(value)
     if len(s) > 19:
      raise ValueError('金额太大了,不知道该怎么表达。')
     istr, dstr = s.split('.')   # 小数部分和整数部分分别处理
     istr = istr[::-1]     # 翻转整数部分字符串
     so = []  # 用于记录转换结果
     
     # 零
     if value == 0:
      return prefix + num[0] + iunit[0]
     haszero = False  # 用于标记零的使用
     if dstr == '00':
      haszero = True # 如果无小数部分,则标记加过零,避免出现“圆零整”
      
     # 处理小数部分
     # 分
     if dstr[1] != '0':
      so.append(dunit[1])
      so.append(num[int(dstr[1])])
     else:
      so.append('整')   # 无分,则加“整”
     # 角
     if dstr[0] != '0':
      so.append(dunit[0])
      so.append(num[int(dstr[0])])
     elif dstr[1] != '0':
      so.append(num[0])  # 无角有分,添加“零”
      haszero = True   # 标记加过零了
      
     # 无整数部分
     if istr == '0':
      if haszero:    # 既然无整数部分,那么去掉角位置上的零
       so.pop()
      so.append(prefix)  # 加前缀
      so.reverse()   # 翻转
      return ''.join(so)
    
     # 处理整数部分
     for i, n in enumerate(istr):
      n = int(n)
      if i % 4 == 0:   # 在圆、万、亿等位上,即使是零,也必须有单位
       if i == 8 and so[-1] == iunit[4]: # 亿和万之间全部为零的情况
        so.pop()      # 去掉万
       so.append(iunit[i])
       if n == 0:       # 处理这些位上为零的情况
        if not haszero:     # 如果以前没有加过零
         so.insert(-1, num[0])  # 则在单位后面加零
         haszero = True    # 标记加过零了
       else:        # 处理不为零的情况
        so.append(num[n])
        haszero = False     # 重新开始标记加零的情况
      else:         # 在其他位置上
       if n != 0:       # 不为零的情况
        so.append(iunit[i])
        so.append(num[n])
        haszero = False     # 重新开始标记加零的情况
       else:        # 处理为零的情况
        if not haszero:     # 如果以前没有加过零
         so.append(num[0])
         haszero = True
    
     # 最终结果
     so.append(prefix)
     so.reverse()
     return ''.join(so)
    js