一、合同模板
![]()
二、合同清单
![]()
三、代码
1 from docx import Document
2 import xlrd
3
4 def change_text(old_text, new_text):
5 all_paragraphs = document.paragraphs # 选取段落
6 for paragraph in all_paragraphs: # 对于段落的替换
7 for run in paragraph.runs: # 选取段落中的块
8 run_text = run.text.replace(old_text, new_text) # 替换
9 run.text = run_text
10
11 all_tables = document.tables
12 for table in all_tables: # 对于表格的替换
13 for row in table.rows:
14 for cell in row.cells:
15 cell_text = cell.text.replace(old_text, new_text)
16 cell.text = cell_text
17
18 xlsx = xlrd.open_workbook(r"D:\python\合同清单.xlsx")
19 sheet = xlsx.sheet_by_index(0)
20
21 for table_row in range(1, sheet.nrows):
22 document = Document(r"D:\python\模板.docx")
23 for table_col in range(0, sheet.ncols):
24 change_text(str(sheet.cell_value(0, table_col)), str(sheet.cell_value(table_row, table_col)))
25
26 document.save("%s合同.docx" % str(sheet.cell_value(table_row, 0)))
27 print("%s合同完成" % str(sheet.cell_value(table_row, 0)))