一、背景需求
搭档问我要中2班上学期的资料,
我把最后的微信优质指导做完,就打包发送了。
因为旧代码和旧Word都卡死在坏掉的电脑里,所以要重做模版
二、Word模版制作
本次把Word模版上传CSDN,备份
三、代码
''' 微信优质家教指导(一页)自动插入8张截图、替换班级、教师名字、时间,统一文件名 作者:阿夏 时间:20261019 ''' from docx import Document from docx.shared import Inches,Cm from PIL import Image import os from docx.enum.text import WD_PARAGRAPH_ALIGNMENT # 打开Word文档 path=r'D:\Python最终内容\202061019微信优质指导' doc = Document(path+r'\微信家教指导模版.docx') # 获取jpg文件夹中的所有图片文件 image_folder = path+r'\微信截图' image_files = os.listdir(image_folder) # 遍历每个表格单元格和对应的图片文件 # 遍历每个表格单元格和对应的图片文件 table = doc.tables[0] # 假设要操作的表格是第一个表格 cell_index = 0 for row in table.rows: for cell in row.cells: if cell_index >= len(image_files): break # 打开并调整图片大小 image_file = os.path.join(image_folder, image_files[cell_index]) image = Image.open(image_file) image.thumbnail(( Cm(6),Cm(10.5))) # 调整图片大小为4x4厘米 # image.thumbnail((Inches(2), Inches(2))) # 调整图片大小为2x2英寸 # 清空单元格中的段落 for paragraph in cell.paragraphs: cell._element.remove(paragraph._element) # 清空单元格中的内容 for paragraph in cell.paragraphs: for run in paragraph.runs: run.text = "" # 将图片插入到单元格中 # cell.add_paragraph().add_run().add_picture(image_file, width=Inches(2), height=Inches(2)) # cell.add_paragraph().add_run().add_picture(image_file, width=Cm(6),height=Cm(11.7)) # 插入图片到单元格中 并居中 paragraph = cell.add_paragraph() paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run = paragraph.add_run() run.add_picture(image_file, width=Cm(6), height=Cm(10.5)) cell_index += 1 # # 保存修改后的Word文档 # doc.save(r'C:\Users\jg2yXRZ\OneDrive\桌面\中X班微信优质指导交流\中4班微信优质指导交流(插图).docx') # 班级、教师、时间的文字替换 original=['X','Y','A','B','T'] new=['中','2','张莉','胡冬茹','2027.1.13'] # 遍历所有段落 for i in range(len(original)): for paragraph in doc.paragraphs: # 遍历段落中的每个运行对象 for run in paragraph.runs: # 替换运行对象中的文本 a="{}".format(original[i]) b="{}".format(new[i]) if "{}".format(a) in run.text: new_text = run.text.replace("{}".format(a) ,"{}".format(b)) # 清空原有运行对象的内容 run.text = "" # 添加替换后的文本,并保留原有格式 new_run = run new_run.text = new_text # 保存修改后的Word文档 doc.save(path+fr'\15_{new[0]}{new[1]}班_微信优质指导_班一份_{new[4]}_(完).docx') # 15_中2班_微信优质指导_班一份_2027.1_(完).docx