一、合同模板
二、合同清單
三、代碼
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)))