from docx import Document
import xlrd
#定义一个方法用来替换
def change_test(old_test,new_test):
#替换所有的段落
all_paragraphs = document.paragraphs
for paragraph in all_paragraphs:
for run in paragraph.runs:
run_test = run.test.replace(old_test,new_test)
run.test = run_test
#替换所有的表格(这是word里面的表格)
all_tables = document.tables
for table in all_tables:
for row in table.rows:
for cell in row.cells:
cell_test = cell.test.replace(old_test,new_test)
cell.test = cell_test
#1.打开信息表格
xlsx = xlrd.open_workbook(‘合同信息表。xlsx’)
sheet = xlsx.sheet_by_index(0)
#2.遍历所有的行,每一行是一个公司的信息
for table_row in range(1,sheet.nrows):
#2.1创建一个word文档
document = Document('模板.docx')
#2.2遍历所有的列
for table_col in range(0,sheet.ncols):
#进行替换,用同一列 下面的信息部分 替换上面的表头信息
change_test(str(sheet.cell_value(0,table_col)),str(sheet.cell_value(table_row,table_col)))
#2.3完成替换,保存文件,用...公司名字保存
document.save("%s合同.docx" % str(sheet.cell_value(table_row,0)))
print("%s合同完成" % str(sheet.cell_value(table_row,0)))