在工作中,可能需要做很多不复杂的合同,即修改合同中的多个合同元素,但是必须逐个打开合同以查找更改。 当合同太多或手头上有其他事物纠缠时,可能会不小心漏掉,忘记填写和修改。在这里可以用python一键解决你的困扰。大大提高工作效率。
生成Word文档版本合同
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx.shared import Pt,Inches
document=Document()
style=document.styles['Normal']
style.font.name='宋体'
style.element.rPr.rFonts.set(qn('w:eastAsia'),'宋体')
title=document.add_paragraph('汽车贷款合同')
title.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER
title.paragraph_format.space_after=Pt(20)
title.style.font.size=Pt(14)
content=document.add_paragraph()
content.paragraph_format.first_line_indent=Pt(20)
partA=content.add_run('itcast01')
content.add_run('(甲方)于')
sign_date=content.add_run('itcast02')
content.add_run('与')
partB=content.add_run('itcast03')
content.add_run('(乙方)签订汽车贷款合同。乙方需要在')
day=content.add_run('itcast04')
content.add_run('天内向甲方支付人民币')
total_money=content.add_run('itcast05')
content.add_run('元来支持甲方购买汽车。甲方需要分为')
times=content.add_run('itcast06')
content.add_run('期来偿还乙方本金。经过友好协商,甲方需要向乙方一次性支付')
fee=content.add_run('itcast07')
content.add_run('元作为汽车贷款金融服务费。')
bottom1=document.add_paragraph('甲方:')
bottom1.alignment=WD_PARAGRAPH_ALIGNMENT.LEFT
bottom1.paragraph_format.left_indent=Inches(4)
bottom2=document.add_paragraph('乙方:')
bottom2.alignment=WD_PARAGRAPH_ALIGNMENT.LEFT
bottom2.paragraph_format.left_indent=Inches(4)
bottom3=document.add_paragraph('日期: 年 月 日')
bottom3.alignment=WD_PARAGRAPH_ALIGNMENT.LEFT
bottom3.paragraph_format.left_indent=Inches(4)
document.save('template.docx')
生成的合同template.docx
一键批量生成合同
from openpyxl import load_workbook
from docx import Document
from os import listdir
'''
定义替换函数
'''
def replace_text(old_text, new_text):
all_paragraphs = document.paragraphs
for paragraph in all_paragraphs:
for run in paragraph.runs:
run_text = run.text.replace(old_text, new_text)
run.text = run_text
all_tables = document.tables
for table in all_tables:
for row in table.rows:
for cell in row.cells:
cell_text = cell.text.replace(old_text, new_text)
cell.text = cell_text
'''
获取Excel和Word的文件
'''
for file in listdir():
if '.xlsx' in file:
xlsx_name = file
if '.docx' in file:
docx_name = file
'''
读取Excel内数据
'''
wb = load_workbook(xlsx_name)
sheetx0 = wb.sheetnames
sheetx = wb[sheetx0[0]]
'''
循环读取并替换
'''
for col in range(2,sheetx.max_column+1):
document = Document(docx_name)
if sheetx.cell(row=1,column=col).value!=None:
for l in range(1,sheetx.max_row+1):
old_text = sheetx.cell(row=l,column=1).value
new_text = sheetx.cell(row=l,column=col).value
replace_text(str(old_text),str(new_text))
filename = str(sheetx.cell(row=1,column=col).value)
document.save("%s.docx"%(filename))
print('合同生成完毕!')
实现效能:把我们需要生成的数据填写在Excel相应部分,然后将自动生成相对应版本的word合同。
生成的合同: