A contract template
Second, the list of contracts
Third, the code
. 1 from docx Import the Document 2 Import to xlrd . 3 . 4 DEF change_text (OLD_TEXT, NEW_TEXT): . 5 all_paragraphs = document.paragraphs # selected paragraph . 6 for paragraph in all_paragraphs: # for replacing paragraph . 7 for RUN in paragraph.runs: # Select paragraphs block . 8 run_text = run.text.replace (OLD_TEXT, NEW_TEXT) # replaced . 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)))