当前位置: 首页 > news >正文

【办公类-53-14】2024年9月周计划系列优化(5天、6天、7天模版)

11月为了迎接普及普惠督导抽查,所有班级资料都要做到第11周。我拿出去年的周计划代码,重新批量一下。

这学期做代码有一个难点——并非全部5天,“国庆节”的4-5周是7天教案放在一个WORD模版上

5天模版(一横三竖=4页)

节日写法

7天模版(一横四竖=5页)

而原版的周计划里面也有6天7天合并的模版

背景需求:

为了能提取5-7天的源文件内容,我花了整整两天调试代码,终于打通了全部流程。

因为每次做周计划,都要微调参数,所以每个代码都不能做在一起

00周次变成2位数.py(根据每年获得的源文件的格式名修改)


'''
先把被抄的原周计划做成“第01周 周计划 春天来了”的样式 ,删除空格,做成两位数样式
'''import os,shutil
import time# 定义路径  
p = r"D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天"  
path1 = p + r"\00doc"  
path2 = p + r"\01doc"  # 确保目标目录存在,如果不存在则创建  
if not os.path.exists(path2):  os.makedirs(path2)  print('--第1,删除空格-----')# 获取path1目录下的文件列表  
fileList = os.listdir(path1)  # 遍历文件列表,进行复制并重命名操作  
for file in fileList:  # 生成原始文件的完整路径  old_file_path = os.path.join(path1, file)  # 删除文件名中的空格,并生成新的文件名  new_file_name = file.replace(" ", "")  new_file_path = os.path.join(path2, new_file_name)  # 复制文件到目标目录,并重命名  shutil.copy2(old_file_path, new_file_path)  # 打印操作结果  print(f"已复制并重命名文件: {old_file_path} -> {new_file_path}")# 延时
time.sleep(5)print('-------第2,添加空格-------')
fileList=os.listdir(path2)print(fileList)for file in fileList:  # 如果格式不统一 提取所有的周次split_str = file.split('(')newname1 = split_str[0]  # _的第0部分=序号 # print(newname1)newname2= split_str[1]  # _的第0部分=序号 # print(newname2)newname=newname1+' ('+newname2print(newname)oldname_path = os.path.join(path2,file)# 文件新路径newname_path = os.path.join(path2,newname)# 新旧对调os.rename(oldname_path, newname_path)# 延时
time.sleep(5)print('-------第3,提取周次变成两位数-----------')
fileList=os.listdir(path2)for file in fileList:   # print(file)   # 第06周 周计划(春天来了).docx  已空格为分割点,split_str = file.split(' ')# 求第1、2周,第8周文字的长度newname2= split_str[0]# print(newname2)newname3= split_str[1]# print(newname3)if len(newname2)==4:      # 第18周newname=newname2+' '+'周计划'+' '+newname3print(newname)  elif len(newname2)==3:      # 第8周# print('yici')newname='第0'+newname2[1:]+' '+'周计划'+' '+newname3print(newname)# elif len(newname2)>5:     # 第1、2周else:newname='第0'+newname2[1]+newname2[-1]+' '+'周计划'+' '+newname3print(newname)oldname_path = os.path.join(path2,file)# 文件新路径newname_path = os.path.join(path2,newname)# 新旧对调os.rename(oldname_path, newname_path)


01 doc转docx.py


'''
先把被抄的原周计划做成“第01周 春天来了”的样式
把第一周六天,一周七天的拆分成5天,左边的格子也要对准,不能多列
教案部分如果是空的,必须补上文字
'''
import os  
from win32com import client as wc  # 路径设置  
path = r"D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天"  
oldpath = os.path.join(path, r'01doc')  # 原文件doc地址  
newpath = os.path.join(path, r'02docx')  # 新文件docx地址  # 确保新路径存在  
if not os.path.exists(newpath):  os.makedirs(newpath)  # 提取所有doc和docx文件的路径  
files = []  
for file in os.listdir(oldpath):  if file.lower().endswith(('.doc', '.docx')) and not file.startswith('~$'):  files.append(os.path.join(oldpath, file))  # 打开并转换文件  
word = wc.Dispatch("Word.Application")  
word.Visible = False  # 设置为False以在后台运行  
try:  for file in files:  print("处理文件:" + file)  doc = word.Documents.Open(file)  # 提取文件名和修改扩展名  base_name = os.path.basename(file)  name, ext = os.path.splitext(base_name)  new_file = os.path.join(newpath, name + '.docx')  # 保存为docx格式  doc.SaveAs(new_file, 12)  # 12表示docx格式  doc.Close()  
except Exception as e:  print(f"发生错误:{e}")  
finally:  word.Quit()


02批量删除旧日docx里面的回车符.py

'''
去掉docx文件里的回车
'''import glob,os
from docx import Document  path = r"D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天"  
docx_files = glob.glob(path + r'\02docx\*.docx')  # 读取所有.docx文件  for file_path in docx_files:  # 遍历每个文件路径  file_name = os.path.basename(file_path)  # 获取文件名  print(f"Processing file: {file_name}")  doc = Document(file_path)  # 打开文档  # 使用列表推导式创建一个新段落列表,排除空段落  new_paragraphs = [p for p in doc.paragraphs if p.text.strip()]  # 清空当前文档的所有段落  doc.paragraphs[:] = []  # 将非空段落添加回文档  for p in new_paragraphs:  doc.add_paragraph(p.text)  doc.save(path+r'\03去掉回车'+"\\"+file_name) 
# # # ————————————————
# # # 版权声明:本文为CSDN博主「lsjweiyi」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
# # # 原文链接:https://blog.csdn.net/lsjweiyi/article/details/121728630

03-00 批量周计划(提取1次doc旧日模板参考内容).py(按照7天的格子提取,如果是5天,不足的格子用‘空格’补全)

'''提取1次旧模版的内容,以7天为准。'''from docx import Documentimport os,timefrom openpyxl import load_workbook
import glob
import re
import xlrdpathall=[]
paths=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
path =paths+r'\03去掉回车'for file_name in os.listdir(path):print(path+'\\'+file_name)pathall.append(path+'\\'+file_name)
print(pathall)
print(len(pathall))# 19# 新建EXCEL
import xlwt 
f = xlwt.Workbook('encoding = utf-8')#设置工作簿编码
sheet1 = f.add_sheet('sheet1',cell_overwrite_ok=True)#创建sheet工作表# 写入标题(以7天为准)titleall=['grade', 'classnum', 'weekhan', 'datelong', 'day1', 'day2', 'day3', 'day4', 'day5','day6', 'day7', 'life', 'life1', 'life2',\'sportcon1', 'sportcon2', 'sportcon3', 'sportcon4', 'sportcon5', 'sportcon6', 'sportcon7','sport1', 'sport2', 'sport3', 'sport4', 'sport5', 'sport6', 'sport7',\'sportzd1', 'sportzd2', 'sportzd3', 'game1', 'game2', 'game3', 'game4', 'game5', 'game6', 'game7', 'gamezd1', 'gamezd2', \'theme', 'theme1', 'theme2', 'gbstudy', 'art', 'gbstudy1', 'gbstudy2', 'gbstudy3', 'jtstudy1', 'jtstudy2', 'jtstudy3', 'jtstudy4', 'jtstudy5', 'jtstudy6', 'jtstudy7', \'gy1', 'gy2', 'fk1', 'pj11', 'fk1nr', 'fk1tz', 'fk2', 'pj21', 'fk2nr', 'fk2tz','dateshort', 'weekshu', \'title1', 'topic11', 'topic12', 'jy1', 'cl1', 'j1gc', \'title2', 'topic21', 'topic22', 'jy2', 'cl2', 'j2gc', \'title3', 'topic31', 'topic32', 'jy3', 'cl3', 'j3gc', \'title4', 'topic41', 'topic42',  'jy4','cl4', 'j4gc',\'title5', 'topic51', 'topic52', 'jy5', 'cl5', 'j5gc',\'title6', 'topic61', 'topic62', 'jy6', 'cl6', 'j6gc',\'title7', 'topic71', 'topic72', 'jy7', 'cl7', 'j7gc',\'fs1', 'fs11', 'fs2', 'fs21','T1','T2','T3','T4','T5','T6','T7']
for l9 in range(len(titleall)):sheet1.write(0,l9,titleall[l9])n=1for h in range(len(pathall)):    # 19份19行LIST=[]path=pathall[h]doc = Document(path)# 鉴别第一张表格有几天(几列),第一周是6天,有10列,第五周是7天,有11列# 如果列特别大,说明原始表的框线有移动,需要对位,或者第一行有很多空格,需要删除# 获取第一张表格  first_table = doc.tables[0]  # 获取第一行(索引从0开始)  first_row = first_table.rows[0]  # 计算第一行中的单元格数量,即表格的列数  num_columns = len(first_row.cells)  # 打印结果  print(f"第{n}张表格有 {num_columns} 列")  # 获取第一行段落文字bt=doc.paragraphs[0].text# print(bt)# 中(5)班  第三周  活动安排LIST.append(bt[0])    # 添加年级LIST.append(bt[2])    # 添加班号if len(bt)==16:LIST.append(bt[8:9])    # 添加周次 大写 如果长度等于15 就是一位数汉字else:LIST.append(bt[8:10])# 获取第一行段落文字rq1=doc.paragraphs[1].textLIST.append(rq1[3:])    # 添加起止日期 
# print(LIST)# ll=['grade','classnum','weekhan','datelong'.]# 获取所有表格对象tables = doc.tables# 获取word中第一个表格(周计划表)table = tables[0]# 不同列的坐标数字d=[9,10,11]    # 五天 六天、七天dl=[8,9,10]        #  列数    # tj=[2,1,0]      # 添加空格数#     # print('-----提取第1张表格(周计划表)里面的内容----------')# 星期Xfor dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for xq in range(3,dl[dd]):xq1 = table.cell(0,xq).text        # K.append(k) LIST.append(xq1)for tx in range(int(tj[dd])):LIST.append('')# print(LIST)
#     # 生活名称l = table.cell(1,4).textprint(l)# 吃点心LIST.append(l)# 生活说明(1格2行,分开) (导入做参考,实际是自己写)ll=table.cell(2,4).text.split('\n')print(ll)
#    ['1.观察值日生在自主午餐环节中帮助阿姨分碗筷、毛巾的情况。', '2.提醒幼儿在自主午餐的过程中不说话,打喷嚏咳嗽要对外。']# 不要“1、”、“2、”L=[]for lll in range(2):    # 一共2条L.append(ll[lll][2:])      #    # 不要“1、”、“2、”LIST.append(ll[lll][2:])   # print(L)#     # ['观察幼儿在吃点心时是否能熟练地使用夹子夹取饼干。', '提醒个别幼儿喝完牛奶擦嘴巴。']# 运动=集体游戏+分散游戏 导入,做参考,需要调整for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for jt in range(3,dl[dd]):jt1 = table.cell(3,jt).text        # K.append(k) print(jt1)  LIST.append(jt1)for tx in range(tj[dd]):LIST.append('')# 集体游戏 for jt2 in range(3,dl[dd]):jt3 = table.cell(4,jt2).text        # K.append(k)        print(jt3)  LIST.append(jt3)for tx in range(tj[dd]):LIST.append('')# 运动观察与指导(导入做参考,实际是自己写)s=table.cell(5,4).text.split('\n')print(s)
# #     # [1.'观察幼儿是否能双手握住曲棍杆将皮球打出一定距离。', '2.观察幼儿是否能寻找皮球的多种玩法。', '3.提醒幼儿注意打曲棍干的安全。']
# #     # 有些序号是自动编号,不占字数。S=[]for sss in range(3):    # 一共3条S.append(s[sss][2:])         # 不要“1、”、“2、”、“3、”LIST.append(s[sss][2:])print(S)
#     # ['幼儿是否能双手握住曲棍杆将皮球打出一定距离。', '幼儿是否能寻找皮球的多种玩法。', '提醒幼儿注意打曲棍干的安全。']#     # 游戏内容 角色游戏 导入做参考,每年都在更换for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for fj in range(3,dl[dd]):fj2 = table.cell(7,fj).text        # K.append(k) # print(xq1)              LIST.append(fj2)for tx in range(int(tj[dd])):LIST.append('') 
#     # 游戏观察与指导(导入做参考,实际是自己写)g=table.cell(8,4).text.split('\n')print(g)# ['1、观察娃娃家的幼儿是否会照顾娃娃,与娃娃互动。', '2、重点观察医生在小医院游戏中,与病人的互动时能否加上一些肢体动作。', '3、观察幼儿角色游戏结束后,能否帮助其他伙伴一同整理材料。']# 有些序号是自动编号,不占字数。G=[]for ggg in range(2):    # 一共3条G.append(g[ggg][2:])         # 不要“1、”、“2、”、“3、”LIST.append(g[ggg][2:]) # print(G)
#     # ['观察娃娃家的幼儿是否会照顾娃娃,与娃娃互动。', '重点观察医生在小医院游戏中,与病人的互动时能否加上一些肢体动作。', '观察幼儿角色游戏结束后,能否帮助其他伙伴一同整理材料。']# 主题和主题说明ti=table.cell(9,4).text.split('\n')print(ti)# ['春天来了', '1、了解春天是个万物生长的季节,关注自然环境的不断变化。', '2、感受大自然美丽的景像,以各种方式表达自己的情感与体验。']# 有些序号是自动编号,不占字数。T=[]# 第1个春天来了,不需要删除序号,直接添加T.append(ti[0])LIST.append(ti[0])for ttt in range(1,3):    # 一共2条主题说明T.append(ti[ttt][2:])         # 不要“1、”、“2、”、LIST.append(ti[ttt][2:])print(T)# ['春天来了', '了解春天是个万物生长的季节,关注自然环境的不断变化。', '感受大自然美丽的景像,以各种方式表达自己的情感与体验。']# 个别化内容(3-5项) 一行多个,全部写入iiii=table.cell(10,4).text.split('\n')print(iiii)     LIST.append(iiii)#  ['电风扇转起来了、漂亮的帽子、绿太阳、大雨小雨、做柳树等']# 美术专用活动室ii8=table.cell(11,4).text.split('\n')print(ii8)     LIST.append(ii8)# 个别化观察与指导(导入做参考,实际是自己写)ii=table.cell(12,4).text.split('\n')# print(ii)  # # ['1.观察幼儿组装各种小电风扇的情况,鼓励幼儿不断进行尝试。', '2.观察幼儿制作帽子的情况,提示幼儿尝试不同的材料进行装饰。', '3.观察幼儿在活动过程中的专注程度,鼓励幼儿专心做自己的事。'] # # # 有些序号是自动编号,不占字数。I=[]for iii1 in range(3):    # 一共3条I.append(ii[iii1][2:])         # 不要“1、”、“2、”、“3、”LIST.append(ii[iii1][2:])print(I)# # ['观察幼儿是否能通过协商分配角色表演故事《三只蝴蝶》。', '观察幼儿是否能看懂图谱,跟着音乐打节奏。']# 集体学习 横向五个格子for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for e in range(3,dl[dd]):k = table.cell(13,e).text        # K.append(k) LIST.append(k)for tx in range(int(tj[dd])):LIST.append('')# ['空中小屋\n(偏语言领域)', '花园里有什么\n(偏科学领域-探究)', '*猴子看猴子做\n(偏艺术领域-音乐)', '*借形想象\n(偏艺术领域-美术)', 'PATHS课程--赞美1(偏社会领域)']# 家园共育(导入做参考,实际是自己写)    yy=table.cell(14,4).text.split('\n')# print(yy)# ['1、为春游活动做准备。', '2、在家长的帮助下学习折一些纸花。', '3、天气转暖,适当地为孩子减少衣服。']# 有些序号是自动编号,不占字数。删除2字符后,可能会少前面几个字Y=[]for yyy in range(2):    # 一共3条Y.append(yy[yyy][2:])         # 不要“1、”、“2、”、“3、”LIST.append(yy[yyy][2:])print(Y)# ['为春游活动做准备。', '在家长的帮助下学习折一些纸花。', '天气转暖,适当地为孩子减少衣服。']# # 反馈与调整(因为5=7天,所以反思格子的Y不固定)for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 ff=table.cell(1,dl[dd]).text.split('\n')print(ff)for j in range(2):# 提取活动1(学习活动、生活活动、游戏活动,运动)运动后面没有活动print(ff[j*4][0:4])   LIST.append(ff[j*4][0:4])    # # 提取身份1print(ff[j*4][10:-1])  LIST.append(ff[j*4][10:-1])# 提取反思1print(ff[j*4+1])LIST.append(ff[j*4+1])# print(LIST)#     # # 提取调整1print(ff[j*4+3])LIST.append(ff[j*4+3])print(LIST)print('-----提取第2-5张表格(教案)里面的内容----------')# 第1周、第20周,或国庆周会出现格子表格不满的情况,需要手动调整# 提取阿拉伯数字的周    # LIST.append(h+1)# 获取第5行段落文字bt2=doc.paragraphs[7].textprint(bt2)# 找到“期”和“第”的位置  短日期start_index = bt2.find('期')end_index = bt2.find('第')# 提取“期”到“第”之间的文字并去掉空格if start_index != -1 and end_index != -1:if start_index < end_index:date1 = bt2[start_index + 1: end_index].strip()print(date1)LIST.append(date1)    # 添加短日期# 找到“期”和“第”的位置  短日期start_index = bt2.find('(')end_index = bt2.find(')')# 提取“期”到“第”之间的文字并去掉空格if start_index != -1 and end_index != -1:if start_index < end_index:date2 = bt2[start_index + 1: end_index].strip()print(date2)LIST.append(date2)    # 添加添加周次# 如果是5天,就读取1-2表,如果是6天,就读取1-3条,如果是7天,就读取1-3条ts=[3,4,4]# 教案部分不足7天的格子要补成空,凑满6片 5天=4 6天=6 7天=6ks=[12,6,0]# 最后一张表(反思)的索引数for dd in range(len(d)):if num_columns==int(d[dd]):        for a in range(1,ts[dd]): # 先提取2张表(  共有3张表,其中第1、2张表提取00和01,第3表提取00)  for b in range(2):        # 表1有两个格子00 01 表2有两个格子00 01table = tables[a]        # 表1 表2 # 有两张表all=table.cell(0,b).text.split('\n')print(len(all))# 看看表格里面的行数,如果等于1行(元宵节放假),就写6个空格if len(all)==1:for tt in range(6):LIST.append('')# 看看表格里面的行数,如果大于1行,就不断写入内容else:# print(all)# 提取活动名称(删除后面的执教人员)fs1 = all[0]start_index = fs1.index(":")+1 end_index = fs1.index("执")title = fs1[start_index:end_index]                # title1 = title.replace(" ", "")LIST.append(title)         # print(title)# 空中小屋等4个题目# 提取活动目标(2行)删除前面的序号topic=[]for to in range(2,4):    # 行数mb=all[to][2:]LIST.append(mb)# topic.append(all[to][2:])# print(topic)# ['理解故事,知道春天是竹笋快速生长的季节。', '乐意想办法帮助小狐狸解决问题,并能大胆表达自己的想法。']# 提取活动准备# (第一种:经验准备)pre1=all[5][5:]LIST.append(pre1)# print(pre)# (第二种:材料准备)pre2=all[6][5:]LIST.append(pre2)# print(pre2)# ppt、故事录音# 提取活动过程pro=all[8:]PRO='\n'.join(pro)# print(PRO)LIST.append(PRO)# 一、我家住几楼---导入主题,激起幼儿兴趣# 1、你们的家住在哪里?住在几楼?为什么买这么高?# 小结:是呀,住这么高的房子可以看到远远的风景。# 2、小狐狸也想住楼房,楼上的房间高高的,远远望去,可以看见一片美景,那该多开心。# 二、房子造在哪?---分段欣赏# for tx in range(int(ks[dd])):#     LIST.append('111') for a in range(int(ts[dd]),int(ts[dd])+1): # 最后提取第3张表的00部分for b in range(1):        # 表1有两个格子00 01 表2有两个格子00 01table = tables[a]        # 表1 表2 # 有两张表all=table.cell(0,b).text.split('\n')if len(all)==1:LIST.append('')# print(all)else:# 提取活动名称(删除后面的执教人员)fs1 = all[0]start_index = fs1.index(":")+1 end_index = fs1.index("执")title = fs1[start_index:end_index]                # title1 = title.replace(" ", "")LIST.append(title)  # print(title)# 空中小屋 只有一个标题# 提取活动目标(2行)删除前面的序号topic=[]for t in range(2,4):    # 行数topic.append(all[t][2:])LIST.append(all[t][2:])# print(topic)# ['理解故事,知道春天是竹笋快速生长的季节。', '乐意想办法帮助小狐狸解决问题,并能大胆表达自己的想法。']# 提取活动准备# (第一种:经验准备)pre1=all[5][5:]LIST.append(pre1)# print(pre)# (第二种:材料准备)pre2=all[6][5:]LIST.append(pre2)# print(pre2)# 提取活动过程pro=all[8:]# print(pro)# # 这是列表样式# ['一、我家住几楼---导入主题,激起幼儿兴趣', '1、你们的家住在哪里?住在几楼?为什么买这么高?', '小结:是呀,住这么高的房子可以看到远远的风景。', '2、小狐狸也想住楼房,楼上的房间高高的,远远望去 # ,可以看见一片美景,那该多开心。', '二、房# 合并列表PRO='\n'.join(pro)# print(PRO)LIST.append(PRO)# 一、我家住几楼---导入主题,激起幼儿兴趣# 1、你们的家住在哪里?住在几楼?为什么买这么高?# 小结:是呀,住这么高的房子可以看到远远的风景。# 2、小狐狸也想住楼房,楼上的房间高高的,远远望去,可以看见一片美景,那该多开心。# 二、房子造在哪?---分段欣赏for tx in range(int(ks[dd])):if int(ks[dd])==6:# 6天3页,但是第4也第一格页要写上教案才能运行。print('tiaoguo')passelse:LIST.append('') for c in range(2):        # 表3的01有两个上下格子  表2有两个格子00 01table = tables[ts[dd]]        # 表3# 有两张表fs=table.cell(c,1).text.split('\n')# print(fs)# 提取反思的课程名字# 提取活动名称(删除后面的执教人员)fs2 = fs[1]start_index = fs2.index(":")+1 end_index = fs2.index("执")fstitle = fs2[start_index:end_index]                # title1 = title.replace(" ", "")# fstitle=fs[1][5:][:-6]# print(fstitle)LIST.append(fstitle)# 纯反思部分(第三行开始)    fs1=fs[2:]# print(fs1)fs3=[]for i in range(len(fs1)):fs4='         '+fs1[i]        # 主动添加缩进2字符# print(fs4)fs3.append(fs4)# 合并列表fs2='\n'.join(fs3)# print(fs2)LIST.append(fs2)extracted_texts = []# 遍历前5张表格for table in doc.tables[:5]:# 获取第1行单元格内容first_row_cells = table.rows[0].cells# 提取“执教:”和回车符之间的文字并去除空格for cell in first_row_cells:cell_text = cell.text.strip()if '执教:' in cell_text:start_index = cell_text.find('执教:') + len('执教:')end_index = cell_text.find('\n')extracted_text = cell_text[start_index:end_index].strip()extracted_texts.append(extracted_text)# 打印提取的文字for T in extracted_texts:print(T)    LIST.append(T)for g in range(len(LIST)):# K =[1,3,4,6,8,10]#要写入的列表的值sheet1.write(n,g,LIST[g])#写入数据参数对应 行,列,值n+=1paths2=paths+r'\09_00 旧版周计划提取信息(导出一次).xls'
f.save(paths2)#保存.x1s到当前工作目录# doc.close(path)time.sleep(5)print('--打开XLSX-,把里面的空格删除,把1、替换成1.--')# # # 关闭Excel文件
# workbook.close()
import xlrd
import xlwt# 打开Excel文件
workbook = xlrd.open_workbook(paths2)worksheet = workbook.sheet_by_index(0)  # 选择要读取的工作表# 创建一个新的Workbook对象
new_workbook = xlwt.Workbook()
new_worksheet = new_workbook.add_sheet('Sheet1')  # 新建一个工作表# 遍历每一行
for row_index in range(worksheet.nrows):row_values = worksheet.row_values(row_index)for col_index, cell_value in enumerate(row_values):if isinstance(cell_value, str):# 清除单元格内文字的格式cell_value = cell_value.strip()# 替换文本for s in range(1, 10):cell_value = cell_value.replace("{}、".format(s), "{}.".format(s))cell_value = cell_value.replace(' ', '')cell_value = cell_value.replace(' ', '')cell_value = cell_value.replace( "  ", '')# # 判断单元格中的文字是否有空格# if ' ' in cell_value:#     # 替换空格为无空格#     cell_value = cell_value.replace(' ', '')# if ' ' in cell_value:#     # 替换空格为无空格#     cell_value = cell_value.replace(' ', '')# 替换文本for s in range(1, 10):cell_value = cell_value.replace("{}、".format(s), "{}.".format(s))# 将修改后的值写入新的Workbook中new_worksheet.write(row_index, col_index, cell_value)# 保存修改后的Excel文件
new_workbook.save(paths2)
new_workbook.save(paths+r'\09_01 旧版周计划提取信息(手动修改).xls')


03-01批量周计划(对第一次WORD模版内容进行格式的手动修改):py(这里是手动修改,文件名与执教中间加四个点空格,教案部分复制四个点的空格、把班级、周次、长短日期、教师复制进去)


# 调整执教的空行
# 把教案反思的人名修改,手动添加四个点的缩进(    英文状态)


03-01 批量周计划(生成第一次WORD模版).py(套用三个WORD模版5、6、7天)

# 一、导入相关模块,设定excel所在文件夹和生成word保存的文件夹
from docxtpl import DocxTemplate
import pandas as pd
import osprint('----1、第一次新WORD制作--------')
path = r"D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天"
print(path)file_path=path+r'\04第一次生成新WORD'
print(file_path)
os.makedirs(file_path,exist_ok=True)print('----计算每一行的数据用5天、6天还是7天的表格------')import xlrd  # 假设 path 是之前已经定义好的文件路径变量的一部分  
file_paths = path + r'\09_01 旧版周计划提取信息(手动修改).xls'  
workbook = xlrd.open_workbook(file_paths)  
sheet = workbook.sheet_by_index(0)  # 获取第一张工作表    # 遍历每一行,从第二行开始(索引为1,因为索引从0开始,但Excel从1开始计数行)  
for row_idx in range(1,sheet.nrows):  # sheet.nrows 返回工作表中的行数  # 读取当前行的E到K列(列索引从0开始,但Excel列从1开始计数,所以E=4, ..., K=10)  row_data = sheet.row_values(row_idx, start_colx=4, end_colx=11)  # print(row_data)# 删除 row_data 中的空元素(None 或空字符串)  days = [cell for cell in row_data if cell is not None and cell != '']  # 统计每行非空元素的数量  (天数)day = len(days)  print(f'第{row_idx}行,本周天数是{day}天')# 如果是5天就用5天模版,如果是7天,就用7天模版tpl = DocxTemplate(path+fr'\12 周计划{day}天_横版.docx')WeeklyPlan = pd.read_excel(path+r'\09_01 旧版周计划提取信息(手动修改).xls')grade = WeeklyPlan["grade"].str.rstrip()classnum =WeeklyPlan["classnum"] # 没有str.rstrip()是数字格式weekhan =WeeklyPlan["weekhan"].str.rstrip() # str.rstrip()都是文字格式# day=WeeklyPlan["day"].str.rstrip() # sc =WeeklyPlan["sc"].str.rstrip() datelong =WeeklyPlan["datelong"].str.rstrip() day1 = WeeklyPlan["day1"].str.rstrip() day2 = WeeklyPlan["day3"].str.rstrip() day3 = WeeklyPlan["day3"].str.rstrip() day4 = WeeklyPlan["day4"].str.rstrip() day5 = WeeklyPlan["day5"].str.rstrip() day6 = WeeklyPlan["day6"].str.rstrip() day7 = WeeklyPlan["day7"].str.rstrip() life = WeeklyPlan["life"].str.rstrip() life1 = WeeklyPlan["life1"].str.rstrip() life2 = WeeklyPlan["life2"].str.rstrip()sportcon1 = WeeklyPlan["sportcon1"].str.rstrip() sportcon2 = WeeklyPlan["sportcon2"].str.rstrip()sportcon3 = WeeklyPlan["sportcon3"].str.rstrip() sportcon4 = WeeklyPlan["sportcon4"].str.rstrip()sportcon5 = WeeklyPlan["sportcon5"].str.rstrip() sportcon6 = WeeklyPlan["sportcon6"].str.rstrip()sportcon7 = WeeklyPlan["sportcon7"].str.rstrip() sport1 = WeeklyPlan["sport1"].str.rstrip() sport2 = WeeklyPlan["sport2"].str.rstrip() sport3 = WeeklyPlan["sport3"].str.rstrip() sport4 = WeeklyPlan["sport4"].str.rstrip() sport5 = WeeklyPlan["sport5"].str.rstrip() sport6 = WeeklyPlan["sport6"].str.rstrip() sport7 = WeeklyPlan["sport7"].str.rstrip() sportzd1 = WeeklyPlan["sportzd1"].str.rstrip() sportzd2 = WeeklyPlan["sportzd2"].str.rstrip()sportzd3 = WeeklyPlan["sportzd3"].str.rstrip()game1 = WeeklyPlan["game1"].str.rstrip() game2 = WeeklyPlan["game2"].str.rstrip() game3 = WeeklyPlan["game3"].str.rstrip() game4 = WeeklyPlan["game4"].str.rstrip() game5 = WeeklyPlan["game5"].str.rstrip() game6 = WeeklyPlan["game6"].str.rstrip() game7 = WeeklyPlan["game7"].str.rstrip() gamezd1 = WeeklyPlan["gamezd1"].str.rstrip() gamezd2 = WeeklyPlan["gamezd2"].str.rstrip() theme= WeeklyPlan["theme"].str.rstrip() theme1= WeeklyPlan["theme1"].str.rstrip() theme2= WeeklyPlan["theme2"].str.rstrip() gbstudy = WeeklyPlan["gbstudy"].str.rstrip()art = WeeklyPlan["art"].str.rstrip()gbstudy1 = WeeklyPlan["gbstudy1"].str.rstrip() gbstudy2 = WeeklyPlan["gbstudy2"].str.rstrip() gbstudy3 = WeeklyPlan["gbstudy3"].str.rstrip() jtstudy1 = WeeklyPlan["jtstudy1"].str.rstrip() jtstudy2 = WeeklyPlan["jtstudy2"].str.rstrip() jtstudy3 = WeeklyPlan["jtstudy3"].str.rstrip() jtstudy4 = WeeklyPlan["jtstudy4"].str.rstrip() jtstudy5 = WeeklyPlan["jtstudy5"].str.rstrip() jtstudy6 = WeeklyPlan["jtstudy6"].str.rstrip() jtstudy7 = WeeklyPlan["jtstudy7"].str.rstrip() gy1 = WeeklyPlan["gy1"].str.rstrip()gy2 = WeeklyPlan["gy2"].str.rstrip()fk1	= WeeklyPlan["fk1"].str.rstrip()pj11 = WeeklyPlan["pj11"].str.rstrip()fk1nr = WeeklyPlan["fk1nr"].str.rstrip()fk1tz = WeeklyPlan["fk1tz"].str.rstrip()fk2 = WeeklyPlan["fk2"].str.rstrip()pj21= WeeklyPlan["pj21"].str.rstrip()fk2nr = WeeklyPlan["fk2nr"].str.rstrip()fk2tz = WeeklyPlan["fk2tz"].str.rstrip()dateshort=WeeklyPlan["dateshort"].str.rstrip() weekshu=WeeklyPlan["weekshu"]# 没有str.rstrip()是数字格式title1 = WeeklyPlan["title1"]# 题目后面有空格,不需要清除topic11 = WeeklyPlan["topic11"].str.rstrip()topic12 = WeeklyPlan["topic12"].str.rstrip()jy1 = WeeklyPlan["jy1"].str.rstrip()cl1 = WeeklyPlan["cl1"].str.rstrip()j1gc= WeeklyPlan["j1gc"].str.rstrip()title2 = WeeklyPlan["title2"]# 题目后面有空格,不需要清除topic21 = WeeklyPlan["topic21"].str.rstrip()topic22 = WeeklyPlan["topic22"].str.rstrip()jy2 = WeeklyPlan["jy2"].str.rstrip()cl2 = WeeklyPlan["cl2"].str.rstrip()j2gc= WeeklyPlan["j2gc"].str.rstrip()title3 = WeeklyPlan["title3"]# 题目后面有空格,不需要清除topic31 = WeeklyPlan["topic31"].str.rstrip()topic32 = WeeklyPlan["topic32"].str.rstrip()jy3 = WeeklyPlan["jy3"].str.rstrip()cl3 = WeeklyPlan["cl3"].str.rstrip()j3gc= WeeklyPlan["j3gc"].str.rstrip()title4 = WeeklyPlan["title4"]# 题目后面有空格,不需要清除topic41 = WeeklyPlan["topic41"].str.rstrip()topic42 = WeeklyPlan["topic42"].str.rstrip()jy4 = WeeklyPlan["jy4"].str.rstrip()cl4 = WeeklyPlan["cl4"].str.rstrip()j4gc= WeeklyPlan["j4gc"].str.rstrip()title5 = WeeklyPlan["title5"]# 题目后面有空格,不需要清除topic51 = WeeklyPlan["topic51"].str.rstrip()topic52 = WeeklyPlan["topic52"].str.rstrip()jy5 = WeeklyPlan["jy5"].str.rstrip()cl5 = WeeklyPlan["cl5"].str.rstrip()j5gc= WeeklyPlan["j5gc"].str.rstrip()title5 = WeeklyPlan["title5"]# 题目后面有空格,不需要清除topic51 = WeeklyPlan["topic51"].str.rstrip()topic52 = WeeklyPlan["topic52"].str.rstrip()jy5 = WeeklyPlan["jy5"].str.rstrip()cl5 = WeeklyPlan["cl5"].str.rstrip()j5gc= WeeklyPlan["j5gc"].str.rstrip()title6 = WeeklyPlan["title6"]# 题目后面有空格,不需要清除topic61 = WeeklyPlan["topic61"].str.rstrip()topic62 = WeeklyPlan["topic62"].str.rstrip()jy6 = WeeklyPlan["jy6"].str.rstrip()cl6 = WeeklyPlan["cl6"].str.rstrip()j6gc= WeeklyPlan["j6gc"].str.rstrip()title7 = WeeklyPlan["title7"]# 题目后面有空格,不需要清除topic71 = WeeklyPlan["topic71"].str.rstrip()topic72 = WeeklyPlan["topic72"].str.rstrip()jy7 = WeeklyPlan["jy7"].str.rstrip()cl7 = WeeklyPlan["cl7"].str.rstrip()j7gc= WeeklyPlan["j7gc"].str.rstrip()fs1 = WeeklyPlan["fs1"]# 题目后面有空格,不需要清除()strfs11= WeeklyPlan["fs11"].str.rstrip()fs2= WeeklyPlan["fs2"]# 题目后面有空格,不需要清除fs21= WeeklyPlan["fs21"].str.rstrip()T1 = WeeklyPlan["T1"].str.rstrip() T2 = WeeklyPlan["T2"].str.rstrip()T3 = WeeklyPlan["T3"].str.rstrip() T4 = WeeklyPlan["T4"].str.rstrip()T5 = WeeklyPlan["T5"].str.rstrip()T6 = WeeklyPlan["T6"].str.rstrip()T7 = WeeklyPlan["T7"].str.rstrip()# 遍历excel行,逐个生成# num = WeeklyPlan.shape[0]# print(num)for i in range(row_idx-1,row_idx):context = {"grade": grade[i],"classnum": classnum[i],"weekhan": weekhan[i],"datelong": datelong[i],"day1": day1[i],"day2": day2[i],"day3": day3[i], "day4": day4[i],"day5": day5[i],"day6": day4[i],"day7": day5[i],"life": life[i],"life1": life1[i],"life2": life2[i],"sportcon1": sportcon1[i],"sportcon2": sportcon2[i],"sportcon3": sportcon3[i],"sportcon4": sportcon4[i],"sportcon5": sportcon5[i],"sportcon6": sportcon6[i],"sportcon7": sportcon7[i],"weekshu": weekshu[i], "sport1": sport1[i],"sport2": sport2[i],"sport3": sport3[i], "sport4": sport4[i],"sport5": sport5[i],"sport6": sport6[i],"sport7": sport7[i],"sportzd1": sportzd1[i],  "sportzd2": sportzd2[i],"sportzd3": sportzd3[i], "game1": game1[i],"game2": game2[i],"game3": game3[i], "game4": game4[i],"game5": game5[i],"game6": game6[i],"game7": game7[i],"gamezd1": gamezd1[i],"gamezd2": gamezd2[i],"theme": theme[i],"theme1": theme1[i],"theme2": theme2[i],"gbstudy": gbstudy[i],"art": art[i],"gbstudy1": gbstudy1[i], "gbstudy2": gbstudy2[i], "gbstudy3": gbstudy3[i], "jtstudy1": jtstudy1[i],"jtstudy2": jtstudy2[i],"jtstudy3": jtstudy3[i],  "jtstudy4": jtstudy4[i],"jtstudy5": jtstudy5[i],  "jtstudy6": jtstudy6[i],"jtstudy7": jtstudy7[i],  "gy1": gy1[i],"gy2": gy2[i],"fk1": fk1[i],"pj11": pj11[i], "fk1nr": fk1nr[i],"fk1tz": fk1tz[i],"fk2": fk2[i],"pj21": pj21[i],"fk2nr": fk2nr[i],"fk2tz":fk2tz[i], "dateshort": dateshort[i],"weekshu": weekshu[i], "title1":title1[i],   "topic11":topic11[i],   "topic12":topic12[i],   "jy1":jy1[i],   "cl1":cl1[i],"j1gc": j1gc[i],"title2":title2[i],   "topic21":topic21[i],   "topic22":topic22[i],   "jy2":jy2[i],   "cl2":cl2[i],   "j2gc": j2gc[i],"title3":title3[i],   "topic31":topic31[i],   "topic32":topic32[i],   "jy3":jy3[i],   "cl3":cl3[i],   "j3gc": j3gc[i],"title4":title4[i],   "topic41":topic41[i],   "topic42":topic42[i],   "jy4":jy4[i],   "cl4":cl4[i] ,  "j4gc": j4gc[i],"title5":title5[i],   "topic51":topic51[i],   "topic52":topic52[i],   "jy5":jy5[i],   "cl5":cl5[i]  ,"j5gc": j5gc[i],"title6":title6[i],   "topic61":topic61[i],   "topic62":topic62[i],   "jy6":jy6[i],   "cl6":cl6[i]  ,"j6gc": j6gc[i],"title7":title7[i],   "topic71":topic71[i],   "topic72":topic72[i],   "jy7":jy7[i],   "cl7":cl7[i]  ,"j7gc": j7gc[i],"fs1": fs1[i],"fs11": fs11[i],"fs2": fs2[i],"fs21": fs21[i]	,"T1": T1[i],  "T2": T2[i],	"T3": T3[i],  "T4": T4[i],"T5": T5[i],"T6": T6[i],"T7": T7[i]}        tpl.render(context)  # 假设 weekshu[i] 是类似于 '4、5' 或 '7' 这样的字符串if isinstance(weekshu[i], str) and len(weekshu[i]) >= 3:  week_part1 = str(weekshu[i]).split('、')[0]  # 分割字符串并取第一部分week_number1 = int(week_part1)  # 转换为整数week_number2=week_number1+1  formatted_week_number = '%02d' % week_number1+'_'+'%02d' % week_number2         tpl.save(file_path+fr"\{formatted_week_number} 第{str(weekhan[i])}周 周计划 {theme[i]}({datelong[i]})({grade[i]}{classnum[i]}班下学期).docx")else:tpl.save(file_path+fr"\{weekshu[i]:02} 第{str(weekhan[i])}周 周计划 {theme[i]}({datelong[i]})({grade[i]}{classnum[i]}班下学期).docx")


03-02 批量周计划(提取第一次生成并修改过的WORD里面的文字到EXCLE).py(这里不需要删除空格)

'''提取1次旧模版的内容,以7天为准。'''from docx import Documentimport os,timefrom openpyxl import load_workbook
import glob
import re
import xlrdpathall=[]
paths=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
path =paths+r'\04第一次生成新WORD'
for file_name in os.listdir(path):print(path+'\\'+file_name)pathall.append(path+'\\'+file_name)
print(pathall)
print(len(pathall))# 19# 新建EXCEL
import xlwt 
f = xlwt.Workbook('encoding = utf-8')#设置工作簿编码
sheet1 = f.add_sheet('sheet1',cell_overwrite_ok=True)#创建sheet工作表# 写入标题(以7天为准)titleall=['grade', 'classnum', 'weekhan', 'datelong', 'day1', 'day2', 'day3', 'day4', 'day5','day6', 'day7', 'life', 'life1', 'life2',\'sportcon1', 'sportcon2', 'sportcon3', 'sportcon4', 'sportcon5', 'sportcon6', 'sportcon7','sport1', 'sport2', 'sport3', 'sport4', 'sport5', 'sport6', 'sport7',\'sportzd1', 'sportzd2', 'sportzd3', 'game1', 'game2', 'game3', 'game4', 'game5', 'game6', 'game7', 'gamezd1', 'gamezd2', \'theme', 'theme1', 'theme2', 'gbstudy', 'art', 'gbstudy1', 'gbstudy2', 'gbstudy3', 'jtstudy1', 'jtstudy2', 'jtstudy3', 'jtstudy4', 'jtstudy5', 'jtstudy6', 'jtstudy7', \'gy1', 'gy2', 'fk1', 'pj11', 'fk1nr', 'fk1tz', 'fk2', 'pj21', 'fk2nr', 'fk2tz','dateshort', 'weekshu', \'title1', 'topic11', 'topic12', 'jy1', 'cl1', 'j1gc', \'title2', 'topic21', 'topic22', 'jy2', 'cl2', 'j2gc', \'title3', 'topic31', 'topic32', 'jy3', 'cl3', 'j3gc', \'title4', 'topic41', 'topic42',  'jy4','cl4', 'j4gc',\'title5', 'topic51', 'topic52', 'jy5', 'cl5', 'j5gc',\'title6', 'topic61', 'topic62', 'jy6', 'cl6', 'j6gc',\'title7', 'topic71', 'topic72', 'jy7', 'cl7', 'j7gc',\'fs1', 'fs11', 'fs2', 'fs21','T1','T2','T3','T4','T5','T6','T7']
for l9 in range(len(titleall)):sheet1.write(0,l9,titleall[l9])n=1for h in range(len(pathall)):    # 19份19行LIST=[]path=pathall[h]doc = Document(path)# 鉴别第一张表格有几天(几列),第一周是6天,有10列,第五周是7天,有11列# 如果列特别大,说明原始表的框线有移动,需要对位,或者第一行有很多空格,需要删除# 获取第一张表格  first_table = doc.tables[0]  # 获取第一行(索引从0开始)  first_row = first_table.rows[0]  # 计算第一行中的单元格数量,即表格的列数  num_columns = len(first_row.cells)  # 打印结果  print(f"第{n}张表格有 {num_columns} 列")  # 获取第一行段落文字bt=doc.paragraphs[0].text# print(bt)# 中(5)班  第三周  活动安排LIST.append(bt[0])    # 添加年级LIST.append(bt[2])    # 添加班号if len(bt)==16:  # 一  添加周次 大写 如果长度等于15 就是一位数汉字LIST.append(bt[8:9])    elif len(bt)==18:LIST.append(bt[8:11])    # 四、五else:  # len(bt)==17 十二LIST.append(bt[8:10])# 获取第一行段落文字rq1=doc.paragraphs[1].textLIST.append(rq1[3:])    # 添加起止日期 
# print(LIST)# ll=['grade','classnum','weekhan','datelong'.]# 获取所有表格对象tables = doc.tables# 获取word中第一个表格(周计划表)table = tables[0]# 不同列的坐标数字d=[9,10,11]    # 五天 六天、七天dl=[8,9,10]        #  列数    # tj=[2,1,0]      # 添加空格数#     # print('-----提取第1张表格(周计划表)里面的内容----------')# 星期Xfor dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for xq in range(3,dl[dd]):xq1 = table.cell(0,xq).text        # K.append(k) LIST.append(xq1)for tx in range(int(tj[dd])):LIST.append('')# print(LIST)
#     # 生活名称l = table.cell(1,4).textprint(l)# 吃点心LIST.append(l)# 生活说明(1格2行,分开) (导入做参考,实际是自己写)ll=table.cell(2,4).text.split('\n')print(ll)
#    ['1.观察值日生在自主午餐环节中帮助阿姨分碗筷、毛巾的情况。', '2.提醒幼儿在自主午餐的过程中不说话,打喷嚏咳嗽要对外。']# 不要“1、”、“2、”L=[]for lll in range(2):    # 一共2条L.append(ll[lll][2:])      #    # 不要“1、”、“2、”LIST.append(ll[lll][2:])   # print(L)#     # ['观察幼儿在吃点心时是否能熟练地使用夹子夹取饼干。', '提醒个别幼儿喝完牛奶擦嘴巴。']# 运动=集体游戏+分散游戏 导入,做参考,需要调整for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for jt in range(3,dl[dd]):jt1 = table.cell(3,jt).text        # K.append(k) print(jt1)  LIST.append(jt1)for tx in range(tj[dd]):LIST.append('')# 集体游戏 for jt2 in range(3,dl[dd]):jt3 = table.cell(4,jt2).text        # K.append(k)        print(jt3)  LIST.append(jt3)for tx in range(tj[dd]):LIST.append('')# 运动观察与指导(导入做参考,实际是自己写)s=table.cell(5,4).text.split('\n')print(s)
# #     # [1.'观察幼儿是否能双手握住曲棍杆将皮球打出一定距离。', '2.观察幼儿是否能寻找皮球的多种玩法。', '3.提醒幼儿注意打曲棍干的安全。']
# #     # 有些序号是自动编号,不占字数。S=[]for sss in range(3):    # 一共3条S.append(s[sss][2:])         # 不要“1、”、“2、”、“3、”LIST.append(s[sss][2:])print(S)
#     # ['幼儿是否能双手握住曲棍杆将皮球打出一定距离。', '幼儿是否能寻找皮球的多种玩法。', '提醒幼儿注意打曲棍干的安全。']#     # 游戏内容 角色游戏 导入做参考,每年都在更换for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for fj in range(3,dl[dd]):fj2 = table.cell(7,fj).text        # K.append(k) # print(xq1)              LIST.append(fj2)for tx in range(int(tj[dd])):LIST.append('') 
#     # 游戏观察与指导(导入做参考,实际是自己写)g=table.cell(8,4).text.split('\n')print(g)# ['1、观察娃娃家的幼儿是否会照顾娃娃,与娃娃互动。', '2、重点观察医生在小医院游戏中,与病人的互动时能否加上一些肢体动作。', '3、观察幼儿角色游戏结束后,能否帮助其他伙伴一同整理材料。']# 有些序号是自动编号,不占字数。G=[]for ggg in range(2):    # 一共3条G.append(g[ggg][2:])         # 不要“1、”、“2、”、“3、”LIST.append(g[ggg][2:]) # print(G)
#     # ['观察娃娃家的幼儿是否会照顾娃娃,与娃娃互动。', '重点观察医生在小医院游戏中,与病人的互动时能否加上一些肢体动作。', '观察幼儿角色游戏结束后,能否帮助其他伙伴一同整理材料。']# 主题和主题说明ti=table.cell(9,4).text.split('\n')print(ti)# ['春天来了', '1、了解春天是个万物生长的季节,关注自然环境的不断变化。', '2、感受大自然美丽的景像,以各种方式表达自己的情感与体验。']# 有些序号是自动编号,不占字数。T=[]# 第1个春天来了,不需要删除序号,直接添加T.append(ti[0])LIST.append(ti[0])for ttt in range(1,3):    # 一共2条主题说明T.append(ti[ttt][2:])         # 不要“1、”、“2、”、LIST.append(ti[ttt][2:])print(T)# ['春天来了', '了解春天是个万物生长的季节,关注自然环境的不断变化。', '感受大自然美丽的景像,以各种方式表达自己的情感与体验。']# 个别化内容(3-5项) 一行多个,全部写入iiii=table.cell(10,4).text.split('\n')print(iiii)     LIST.append(iiii)#  ['电风扇转起来了、漂亮的帽子、绿太阳、大雨小雨、做柳树等']# 美术专用活动室ii8=table.cell(11,4).text.split('\n')print(ii8)     LIST.append(ii8)# 个别化观察与指导(导入做参考,实际是自己写)ii=table.cell(12,4).text.split('\n')# print(ii)  # # ['1.观察幼儿组装各种小电风扇的情况,鼓励幼儿不断进行尝试。', '2.观察幼儿制作帽子的情况,提示幼儿尝试不同的材料进行装饰。', '3.观察幼儿在活动过程中的专注程度,鼓励幼儿专心做自己的事。'] # # # 有些序号是自动编号,不占字数。I=[]for iii1 in range(3):    # 一共3条I.append(ii[iii1][2:])         # 不要“1、”、“2、”、“3、”LIST.append(ii[iii1][2:])print(I)# # ['观察幼儿是否能通过协商分配角色表演故事《三只蝴蝶》。', '观察幼儿是否能看懂图谱,跟着音乐打节奏。']# 集体学习 横向五个格子for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for e in range(3,dl[dd]):k = table.cell(13,e).text        # K.append(k) LIST.append(k)for tx in range(int(tj[dd])):LIST.append('')# ['空中小屋\n(偏语言领域)', '花园里有什么\n(偏科学领域-探究)', '*猴子看猴子做\n(偏艺术领域-音乐)', '*借形想象\n(偏艺术领域-美术)', 'PATHS课程--赞美1(偏社会领域)']# 家园共育(导入做参考,实际是自己写)    yy=table.cell(14,4).text.split('\n')# print(yy)# ['1、为春游活动做准备。', '2、在家长的帮助下学习折一些纸花。', '3、天气转暖,适当地为孩子减少衣服。']# 有些序号是自动编号,不占字数。删除2字符后,可能会少前面几个字Y=[]for yyy in range(2):    # 一共3条Y.append(yy[yyy][2:])         # 不要“1、”、“2、”、“3、”LIST.append(yy[yyy][2:])print(Y)# ['为春游活动做准备。', '在家长的帮助下学习折一些纸花。', '天气转暖,适当地为孩子减少衣服。']# # 反馈与调整(因为5=7天,所以反思格子的Y不固定)for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 ff=table.cell(1,dl[dd]).text.split('\n')print(ff)for j in range(2):# 提取活动1(学习活动、生活活动、游戏活动,运动)运动后面没有活动print(ff[j*4][0:4])   LIST.append(ff[j*4][0:4])    # # 提取身份1print(ff[j*4][10:-1])  LIST.append(ff[j*4][10:-1])# 提取反思1print(ff[j*4+1])LIST.append(ff[j*4+1])# print(LIST)#     # # 提取调整1print(ff[j*4+3])LIST.append(ff[j*4+3])print(LIST)print('-----提取第2-5张表格(教案)里面的内容----------')# 第1周、第20周,或国庆周会出现格子表格不满的情况,需要手动调整# 提取阿拉伯数字的周    # LIST.append(h+1)# 获取第6行段落文字,一份教案的所有教案表格上面的日期和班级都一样# word模版问题,7天的模版的教案标题在第7行,if num_columns==11:bt2=doc.paragraphs[7].textprint(bt2)# word模版问题,5天的模版的教案标题在第6行,else:bt2=doc.paragraphs[6].textprint(bt2)# 找到“期”和“第”的位置  短日期start_index = bt2.find('期')end_index = bt2.find('第')# 提取“期”到“第”之间的文字并去掉空格if start_index != -1 and end_index != -1:if start_index < end_index:date1 = bt2[start_index + 1: end_index].strip()print(date1)LIST.append(date1)    # 添加短日期# 找到“期”和“第”的位置  短日期start_index = bt2.find('(')end_index = bt2.find(')')# 提取“期”到“第”之间的文字并去掉空格if start_index != -1 and end_index != -1:if start_index < end_index:date2 = bt2[start_index + 1: end_index].strip()print(date2)LIST.append(str(date2))    # 添加添加周次# 如果是5天,就读取1-2表,如果是6天,就读取1-3条,如果是7天,就读取1-3条ts=[3,4,4]# 教案部分不足7天的格子要补成空,凑满6片 5天=4 6天=6 7天=6ks=[12,6,0]# 最后一张表(反思)的索引数for dd in range(len(d)):if num_columns==int(d[dd]):        for a in range(1,ts[dd]): # 先提取2张表(  共有3张表,其中第1、2张表提取00和01,第3表提取00)  for b in range(2):        # 表1有两个格子00 01 表2有两个格子00 01table = tables[a]        # 表1 表2 # 有两张表all=table.cell(0,b).text.split('\n')print(len(all))# 看看表格里面的行数,如果等于1行(元宵节放假),就写6个空格if len(all)==1:for tt in range(6):LIST.append('')# 看看表格里面的行数,如果大于1行,就不断写入内容else:# print(all)# 提取活动名称(删除后面的执教人员)fs1 = all[0]start_index = fs1.index(":")+1 end_index = fs1.index("执")title = fs1[start_index:end_index]                # title1 = title.replace(" ", "")LIST.append(title)         # print(title)# 空中小屋等4个题目# 提取活动目标(2行)删除前面的序号topic=[]for to in range(2,4):    # 行数mb=all[to][2:]LIST.append(mb)# topic.append(all[to][2:])# print(topic)# ['理解故事,知道春天是竹笋快速生长的季节。', '乐意想办法帮助小狐狸解决问题,并能大胆表达自己的想法。']# 提取活动准备# (第一种:经验准备)pre1=all[5][7:]LIST.append(pre1)# print(pre)# (第二种:材料准备)pre2=all[6][7:]LIST.append(pre2)# print(pre2)# ppt、故事录音# 提取活动过程pro=all[8:]PRO='\n'.join(pro)# print(PRO)LIST.append(PRO)# 一、我家住几楼---导入主题,激起幼儿兴趣# 1、你们的家住在哪里?住在几楼?为什么买这么高?# 小结:是呀,住这么高的房子可以看到远远的风景。# 2、小狐狸也想住楼房,楼上的房间高高的,远远望去,可以看见一片美景,那该多开心。# 二、房子造在哪?---分段欣赏# for tx in range(int(ks[dd])):#     LIST.append('111') for a in range(int(ts[dd]),int(ts[dd])+1): # 最后提取第3张表的00部分for b in range(1):        # 表1有两个格子00 01 表2有两个格子00 01table = tables[a]        # 表1 表2 # 有两张表all=table.cell(0,b).text.split('\n')if len(all)==1:LIST.append('')# print(all)else:# 提取活动名称(删除后面的执教人员)fs1 = all[0]start_index = fs1.index(":")+1 end_index = fs1.index("执")title = fs1[start_index:end_index]                # title1 = title.replace(" ", "")LIST.append(title)  # print(title)# 空中小屋 只有一个标题# 提取活动目标(2行)删除前面的序号topic=[]for t in range(2,4):    # 行数topic.append(all[t][2:])LIST.append(all[t][2:])# print(topic)# ['理解故事,知道春天是竹笋快速生长的季节。', '乐意想办法帮助小狐狸解决问题,并能大胆表达自己的想法。']# 提取活动准备# (第一种:经验准备)pre1=all[5][7:]LIST.append(pre1)# print(pre)# (第二种:材料准备)pre2=all[6][7:]LIST.append(pre2)# print(pre2)# 提取活动过程pro=all[8:]# print(pro)# # 这是列表样式# ['一、我家住几楼---导入主题,激起幼儿兴趣', '1、你们的家住在哪里?住在几楼?为什么买这么高?', '小结:是呀,住这么高的房子可以看到远远的风景。', '2、小狐狸也想住楼房,楼上的房间高高的,远远望去 # ,可以看见一片美景,那该多开心。', '二、房# 合并列表PRO='\n'.join(pro)# print(PRO)LIST.append(PRO)# 一、我家住几楼---导入主题,激起幼儿兴趣# 1、你们的家住在哪里?住在几楼?为什么买这么高?# 小结:是呀,住这么高的房子可以看到远远的风景。# 2、小狐狸也想住楼房,楼上的房间高高的,远远望去,可以看见一片美景,那该多开心。# 二、房子造在哪?---分段欣赏for tx in range(int(ks[dd])):if int(ks[dd])==6:# 6天3页,但是第4也第一格页要写上教案才能运行。print('tiaoguo')passelse:LIST.append('') for c in range(2):        # 表3的01有两个上下格子  表2有两个格子00 01table = tables[ts[dd]]        # 表3# 有两张表fs=table.cell(c,1).text.split('\n')# print(fs)# 提取反思的课程名字# 提取活动名称(删除后面的执教人员)fs2 = fs[1]start_index = fs2.index(":")+1 end_index = fs2.index("执")fstitle = fs2[start_index:end_index]                # title1 = title.replace(" ", "")# fstitle=fs[1][5:][:-6]# print(fstitle)LIST.append(fstitle)# 纯反思部分(第三行开始)    fs1=fs[2:]# print(fs1)fs3=[]for i in range(len(fs1)):fs4=fs1[i]        # 教案反思里手动添加四个回车# print(fs4)fs3.append(fs4)# 合并列表fs2='\n'.join(fs3)# print(fs2)LIST.append(fs2)extracted_texts = []# 遍历前5张表格for table in doc.tables[:5]:# 获取第1行单元格内容first_row_cells = table.rows[0].cells# 提取“执教:”和回车符之间的文字并去除空格for cell in first_row_cells:cell_text = cell.text.strip()if '执教:' in cell_text:start_index = cell_text.find('执教:') + len('执教:')end_index = cell_text.find('\n')extracted_text = cell_text[start_index:end_index].strip()extracted_texts.append(extracted_text)# 打印提取的文字for T in extracted_texts:print(T)    LIST.append(T)for g in range(len(LIST)):# K =[1,3,4,6,8,10]#要写入的列表的值sheet1.write(n,g,LIST[g])#写入数据参数对应 行,列,值n+=1paths2=paths+r'\09_02 新版周计划提取信息(反复多次).xls'
f.save(paths2)#保存.x1s到当前工作目录# # doc.close(path)# time.sleep(5)
# 不要删除空格了# print('--打开XLSX-,把里面的空格删除,把1、替换成1.--')# # # # 关闭Excel文件
# # workbook.close()
# import xlrd
# import xlwt# # 打开Excel文件
# workbook = xlrd.open_workbook(paths2)# worksheet = workbook.sheet_by_index(0)  # 选择要读取的工作表# # 创建一个新的Workbook对象
# new_workbook = xlwt.Workbook()
# new_worksheet = new_workbook.add_sheet('Sheet1')  # 新建一个工作表# # 遍历每一行
# for row_index in range(worksheet.nrows):
#     row_values = worksheet.row_values(row_index)
#     for col_index, cell_value in enumerate(row_values):
#         if isinstance(cell_value, str):
#             # 清除单元格内文字的格式
#             cell_value = cell_value.strip()#             # 替换文本
#             for s in range(1, 10):
#                 cell_value = cell_value.replace("{}、".format(s), "{}.".format(s))#             cell_value = cell_value.replace(' ', '')
#             cell_value = cell_value.replace(' ', '')
#             cell_value = cell_value.replace( "  ", '')#             # # 判断单元格中的文字是否有空格
#             # if ' ' in cell_value:
#             #     # 替换空格为无空格
#             #     cell_value = cell_value.replace(' ', '')#             # if ' ' in cell_value:
#             #     # 替换空格为无空格
#             #     cell_value = cell_value.replace(' ', '')#             # 替换文本
#             for s in range(1, 10):
#                 cell_value = cell_value.replace("{}、".format(s), "{}.".format(s))#         # 将修改后的值写入新的Workbook中
#         new_worksheet.write(row_index, col_index, cell_value)# # 保存修改后的Excel文件
# new_workbook.save(paths2)
# new_workbook.save(paths+r'\09_01 旧版周计划提取信息(手动修改).xls')


03-03 批量周计划(生成第二次WORD模版循环).py

# 一、导入相关模块,设定excel所在文件夹和生成word保存的文件夹
from docxtpl import DocxTemplate
import pandas as pd
import osprint('----1、第一次新WORD制作--------')
path = r"D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天"
print(path)file_path=path+r'\05第二次生成新WORD(循环)'
print(file_path)
os.makedirs(file_path,exist_ok=True)print('----计算每一行的数据用5天、6天还是7天的表格------')import xlrd  # 假设 path 是之前已经定义好的文件路径变量的一部分  
file_paths = path + r'\09_02 新版周计划提取信息(反复多次).xls'  
workbook = xlrd.open_workbook(file_paths)  
sheet = workbook.sheet_by_index(0)  # 获取第一张工作表    # 遍历每一行,从第二行开始(索引为1,因为索引从0开始,但Excel从1开始计数行)  
for row_idx in range(1,sheet.nrows):  # sheet.nrows 返回工作表中的行数  # 读取当前行的E到K列(列索引从0开始,但Excel列从1开始计数,所以E=4, ..., K=10)  row_data = sheet.row_values(row_idx, start_colx=4, end_colx=11)  # print(row_data)# 删除 row_data 中的空元素(None 或空字符串)  days = [cell for cell in row_data if cell is not None and cell != '']  # 统计每行非空元素的数量  (天数)day = len(days)  print(f'第{row_idx}行,本周天数是{day}天')# 如果是5天就用5天模版,如果是7天,就用7天模版tpl = DocxTemplate(path+fr'\12 周计划{day}天_横版.docx')WeeklyPlan = pd.read_excel(path+r'\09_02 新版周计划提取信息(反复多次).xls')grade = WeeklyPlan["grade"].str.rstrip()classnum =WeeklyPlan["classnum"] # 没有str.rstrip()是数字格式weekhan =WeeklyPlan["weekhan"].str.rstrip() # str.rstrip()都是文字格式# day=WeeklyPlan["day"].str.rstrip() # sc =WeeklyPlan["sc"].str.rstrip() datelong =WeeklyPlan["datelong"].str.rstrip() day1 = WeeklyPlan["day1"].str.rstrip() day2 = WeeklyPlan["day3"].str.rstrip() day3 = WeeklyPlan["day3"].str.rstrip() day4 = WeeklyPlan["day4"].str.rstrip() day5 = WeeklyPlan["day5"].str.rstrip() day6 = WeeklyPlan["day6"].str.rstrip() day7 = WeeklyPlan["day7"].str.rstrip() life = WeeklyPlan["life"].str.rstrip() life1 = WeeklyPlan["life1"].str.rstrip() life2 = WeeklyPlan["life2"].str.rstrip()sportcon1 = WeeklyPlan["sportcon1"].str.rstrip() sportcon2 = WeeklyPlan["sportcon2"].str.rstrip()sportcon3 = WeeklyPlan["sportcon3"].str.rstrip() sportcon4 = WeeklyPlan["sportcon4"].str.rstrip()sportcon5 = WeeklyPlan["sportcon5"].str.rstrip() sportcon6 = WeeklyPlan["sportcon6"].str.rstrip()sportcon7 = WeeklyPlan["sportcon7"].str.rstrip() sport1 = WeeklyPlan["sport1"].str.rstrip() sport2 = WeeklyPlan["sport2"].str.rstrip() sport3 = WeeklyPlan["sport3"].str.rstrip() sport4 = WeeklyPlan["sport4"].str.rstrip() sport5 = WeeklyPlan["sport5"].str.rstrip() sport6 = WeeklyPlan["sport6"].str.rstrip() sport7 = WeeklyPlan["sport7"].str.rstrip() sportzd1 = WeeklyPlan["sportzd1"].str.rstrip() sportzd2 = WeeklyPlan["sportzd2"].str.rstrip()sportzd3 = WeeklyPlan["sportzd3"].str.rstrip()game1 = WeeklyPlan["game1"].str.rstrip() game2 = WeeklyPlan["game2"].str.rstrip() game3 = WeeklyPlan["game3"].str.rstrip() game4 = WeeklyPlan["game4"].str.rstrip() game5 = WeeklyPlan["game5"].str.rstrip() game6 = WeeklyPlan["game6"].str.rstrip() game7 = WeeklyPlan["game7"].str.rstrip() gamezd1 = WeeklyPlan["gamezd1"].str.rstrip() gamezd2 = WeeklyPlan["gamezd2"].str.rstrip() theme= WeeklyPlan["theme"].str.rstrip() theme1= WeeklyPlan["theme1"].str.rstrip() theme2= WeeklyPlan["theme2"].str.rstrip() gbstudy = WeeklyPlan["gbstudy"].str.rstrip()art = WeeklyPlan["art"].str.rstrip()gbstudy1 = WeeklyPlan["gbstudy1"].str.rstrip() gbstudy2 = WeeklyPlan["gbstudy2"].str.rstrip() gbstudy3 = WeeklyPlan["gbstudy3"].str.rstrip() jtstudy1 = WeeklyPlan["jtstudy1"].str.rstrip() jtstudy2 = WeeklyPlan["jtstudy2"].str.rstrip() jtstudy3 = WeeklyPlan["jtstudy3"].str.rstrip() jtstudy4 = WeeklyPlan["jtstudy4"].str.rstrip() jtstudy5 = WeeklyPlan["jtstudy5"].str.rstrip() jtstudy6 = WeeklyPlan["jtstudy6"].str.rstrip() jtstudy7 = WeeklyPlan["jtstudy7"].str.rstrip() gy1 = WeeklyPlan["gy1"].str.rstrip()gy2 = WeeklyPlan["gy2"].str.rstrip()fk1	= WeeklyPlan["fk1"].str.rstrip()pj11 = WeeklyPlan["pj11"].str.rstrip()fk1nr = WeeklyPlan["fk1nr"].str.rstrip()fk1tz = WeeklyPlan["fk1tz"].str.rstrip()fk2 = WeeklyPlan["fk2"].str.rstrip()pj21= WeeklyPlan["pj21"].str.rstrip()fk2nr = WeeklyPlan["fk2nr"].str.rstrip()fk2tz = WeeklyPlan["fk2tz"].str.rstrip()dateshort=WeeklyPlan["dateshort"].str.rstrip() weekshu=WeeklyPlan["weekshu"]# 没有str.rstrip()是数字格式title1 = WeeklyPlan["title1"]# 题目后面有空格,不需要清除topic11 = WeeklyPlan["topic11"].str.rstrip()topic12 = WeeklyPlan["topic12"].str.rstrip()jy1 = WeeklyPlan["jy1"].str.rstrip()cl1 = WeeklyPlan["cl1"].str.rstrip()j1gc= WeeklyPlan["j1gc"].str.rstrip()title2 = WeeklyPlan["title2"]# 题目后面有空格,不需要清除topic21 = WeeklyPlan["topic21"].str.rstrip()topic22 = WeeklyPlan["topic22"].str.rstrip()jy2 = WeeklyPlan["jy2"].str.rstrip()cl2 = WeeklyPlan["cl2"].str.rstrip()j2gc= WeeklyPlan["j2gc"].str.rstrip()title3 = WeeklyPlan["title3"]# 题目后面有空格,不需要清除topic31 = WeeklyPlan["topic31"].str.rstrip()topic32 = WeeklyPlan["topic32"].str.rstrip()jy3 = WeeklyPlan["jy3"].str.rstrip()cl3 = WeeklyPlan["cl3"].str.rstrip()j3gc= WeeklyPlan["j3gc"].str.rstrip()title4 = WeeklyPlan["title4"]# 题目后面有空格,不需要清除topic41 = WeeklyPlan["topic41"].str.rstrip()topic42 = WeeklyPlan["topic42"].str.rstrip()jy4 = WeeklyPlan["jy4"].str.rstrip()cl4 = WeeklyPlan["cl4"].str.rstrip()j4gc= WeeklyPlan["j4gc"].str.rstrip()title5 = WeeklyPlan["title5"]# 题目后面有空格,不需要清除topic51 = WeeklyPlan["topic51"].str.rstrip()topic52 = WeeklyPlan["topic52"].str.rstrip()jy5 = WeeklyPlan["jy5"].str.rstrip()cl5 = WeeklyPlan["cl5"].str.rstrip()j5gc= WeeklyPlan["j5gc"].str.rstrip()title5 = WeeklyPlan["title5"]# 题目后面有空格,不需要清除topic51 = WeeklyPlan["topic51"].str.rstrip()topic52 = WeeklyPlan["topic52"].str.rstrip()jy5 = WeeklyPlan["jy5"].str.rstrip()cl5 = WeeklyPlan["cl5"].str.rstrip()j5gc= WeeklyPlan["j5gc"].str.rstrip()title6 = WeeklyPlan["title6"]# 题目后面有空格,不需要清除topic61 = WeeklyPlan["topic61"].str.rstrip()topic62 = WeeklyPlan["topic62"].str.rstrip()jy6 = WeeklyPlan["jy6"].str.rstrip()cl6 = WeeklyPlan["cl6"].str.rstrip()j6gc= WeeklyPlan["j6gc"].str.rstrip()title7 = WeeklyPlan["title7"]# 题目后面有空格,不需要清除topic71 = WeeklyPlan["topic71"].str.rstrip()topic72 = WeeklyPlan["topic72"].str.rstrip()jy7 = WeeklyPlan["jy7"].str.rstrip()cl7 = WeeklyPlan["cl7"].str.rstrip()j7gc= WeeklyPlan["j7gc"].str.rstrip()fs1 = WeeklyPlan["fs1"]# 题目后面有空格,不需要清除()strfs11= WeeklyPlan["fs11"].str.rstrip()fs2= WeeklyPlan["fs2"]# 题目后面有空格,不需要清除fs21= WeeklyPlan["fs21"].str.rstrip()T1 = WeeklyPlan["T1"].str.rstrip() T2 = WeeklyPlan["T2"].str.rstrip()T3 = WeeklyPlan["T3"].str.rstrip() T4 = WeeklyPlan["T4"].str.rstrip()T5 = WeeklyPlan["T5"].str.rstrip()T6 = WeeklyPlan["T6"].str.rstrip()T7 = WeeklyPlan["T7"].str.rstrip()# 遍历excel行,逐个生成# num = WeeklyPlan.shape[0]# print(num)for i in range(row_idx-1,row_idx):context = {"grade": grade[i],"classnum": classnum[i],"weekhan": weekhan[i],"datelong": datelong[i],"day1": day1[i],"day2": day2[i],"day3": day3[i], "day4": day4[i],"day5": day5[i],"day6": day4[i],"day7": day5[i],"life": life[i],"life1": life1[i],"life2": life2[i],"sportcon1": sportcon1[i],"sportcon2": sportcon2[i],"sportcon3": sportcon3[i],"sportcon4": sportcon4[i],"sportcon5": sportcon5[i],"sportcon6": sportcon6[i],"sportcon7": sportcon7[i],"weekshu": weekshu[i], "sport1": sport1[i],"sport2": sport2[i],"sport3": sport3[i], "sport4": sport4[i],"sport5": sport5[i],"sport6": sport6[i],"sport7": sport7[i],"sportzd1": sportzd1[i],  "sportzd2": sportzd2[i],"sportzd3": sportzd3[i], "game1": game1[i],"game2": game2[i],"game3": game3[i], "game4": game4[i],"game5": game5[i],"game6": game6[i],"game7": game7[i],"gamezd1": gamezd1[i],"gamezd2": gamezd2[i],"theme": theme[i],"theme1": theme1[i],"theme2": theme2[i],"gbstudy": gbstudy[i],"art": art[i],"gbstudy1": gbstudy1[i], "gbstudy2": gbstudy2[i], "gbstudy3": gbstudy3[i], "jtstudy1": jtstudy1[i],"jtstudy2": jtstudy2[i],"jtstudy3": jtstudy3[i],  "jtstudy4": jtstudy4[i],"jtstudy5": jtstudy5[i],  "jtstudy6": jtstudy6[i],"jtstudy7": jtstudy7[i],  "gy1": gy1[i],"gy2": gy2[i],"fk1": fk1[i],"pj11": pj11[i], "fk1nr": fk1nr[i],"fk1tz": fk1tz[i],"fk2": fk2[i],"pj21": pj21[i],"fk2nr": fk2nr[i],"fk2tz":fk2tz[i], "dateshort": dateshort[i],"weekshu": weekshu[i], "title1":title1[i],   "topic11":topic11[i],   "topic12":topic12[i],   "jy1":jy1[i],   "cl1":cl1[i],"j1gc": j1gc[i],"title2":title2[i],   "topic21":topic21[i],   "topic22":topic22[i],   "jy2":jy2[i],   "cl2":cl2[i],   "j2gc": j2gc[i],"title3":title3[i],   "topic31":topic31[i],   "topic32":topic32[i],   "jy3":jy3[i],   "cl3":cl3[i],   "j3gc": j3gc[i],"title4":title4[i],   "topic41":topic41[i],   "topic42":topic42[i],   "jy4":jy4[i],   "cl4":cl4[i] ,  "j4gc": j4gc[i],"title5":title5[i],   "topic51":topic51[i],   "topic52":topic52[i],   "jy5":jy5[i],   "cl5":cl5[i]  ,"j5gc": j5gc[i],"title6":title6[i],   "topic61":topic61[i],   "topic62":topic62[i],   "jy6":jy6[i],   "cl6":cl6[i]  ,"j6gc": j6gc[i],"title7":title7[i],   "topic71":topic71[i],   "topic72":topic72[i],   "jy7":jy7[i],   "cl7":cl7[i]  ,"j7gc": j7gc[i],"fs1": fs1[i],"fs11": fs11[i],"fs2": fs2[i],"fs21": fs21[i]	,"T1": T1[i],  "T2": T2[i],	"T3": T3[i],  "T4": T4[i],"T5": T5[i],"T6": T6[i],"T7": T7[i]}        tpl.render(context)  # 假设 weekshu[i] 是类似于 '4、5' 或 '7' 这样的字符串if isinstance(weekshu[i], str) and len(weekshu[i]) >= 3:  week_part1 = str(weekshu[i]).split('、')[0]  # 分割字符串并取第一部分week_number1 = int(week_part1)  # 转换为整数week_number2=week_number1+1  formatted_week_number = '%02d' % week_number1+'_'+'%02d' % week_number2         tpl.save(file_path+fr"\{formatted_week_number} 第{str(weekhan[i])}周 周计划 {theme[i]}({datelong[i]})({grade[i]}{classnum[i]}班下学期).docx")else:week_part1 = str(weekshu[i])# 分割字符串并取第一部分week_number1 = int(week_part1)  # 转换为整数            formatted_week_number = '%02d' % week_number1  tpl.save(file_path+fr"\{formatted_week_number} 第{str(weekhan[i])}周 周计划 {theme[i]}({datelong[i]})({grade[i]}{classnum[i]}班下学期).docx")


03-04 批量周计划(提取第二次生成WORD并惨改过的WORD里面的文字到同一个EXCLE).py(脱离原来的09-01,就在05与09-02中反复循环生成)

'''提取1次旧模版的内容,以7天为准。'''from docx import Documentimport os,timefrom openpyxl import load_workbook
import glob
import re
import xlrdpathall=[]
paths=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
path =paths+r'\05第二次生成新WORD(循环)'# 最初是在上面文件夹里循环,# path =paths+r'\06第二次生成新WORD的加粗'# 改到教案部分,可以用加粗的进行更改
for file_name in os.listdir(path):print(path+'\\'+file_name)pathall.append(path+'\\'+file_name)
print(pathall)
print(len(pathall))# 19# 新建EXCEL
import xlwt 
f = xlwt.Workbook('encoding = utf-8')#设置工作簿编码
sheet1 = f.add_sheet('sheet1',cell_overwrite_ok=True)#创建sheet工作表# 写入标题(以7天为准)titleall=['grade', 'classnum', 'weekhan', 'datelong', 'day1', 'day2', 'day3', 'day4', 'day5','day6', 'day7', 'life', 'life1', 'life2',\'sportcon1', 'sportcon2', 'sportcon3', 'sportcon4', 'sportcon5', 'sportcon6', 'sportcon7','sport1', 'sport2', 'sport3', 'sport4', 'sport5', 'sport6', 'sport7',\'sportzd1', 'sportzd2', 'sportzd3', 'game1', 'game2', 'game3', 'game4', 'game5', 'game6', 'game7', 'gamezd1', 'gamezd2', \'theme', 'theme1', 'theme2', 'gbstudy', 'art', 'gbstudy1', 'gbstudy2', 'gbstudy3', 'jtstudy1', 'jtstudy2', 'jtstudy3', 'jtstudy4', 'jtstudy5', 'jtstudy6', 'jtstudy7', \'gy1', 'gy2', 'fk1', 'pj11', 'fk1nr', 'fk1tz', 'fk2', 'pj21', 'fk2nr', 'fk2tz','dateshort', 'weekshu', \'title1', 'topic11', 'topic12', 'jy1', 'cl1', 'j1gc', \'title2', 'topic21', 'topic22', 'jy2', 'cl2', 'j2gc', \'title3', 'topic31', 'topic32', 'jy3', 'cl3', 'j3gc', \'title4', 'topic41', 'topic42',  'jy4','cl4', 'j4gc',\'title5', 'topic51', 'topic52', 'jy5', 'cl5', 'j5gc',\'title6', 'topic61', 'topic62', 'jy6', 'cl6', 'j6gc',\'title7', 'topic71', 'topic72', 'jy7', 'cl7', 'j7gc',\'fs1', 'fs11', 'fs2', 'fs21','T1','T2','T3','T4','T5','T6','T7']
for l9 in range(len(titleall)):sheet1.write(0,l9,titleall[l9])n=1for h in range(len(pathall)):    # 19份19行LIST=[]path=pathall[h]doc = Document(path)# 鉴别第一张表格有几天(几列),第一周是6天,有10列,第五周是7天,有11列# 如果列特别大,说明原始表的框线有移动,需要对位,或者第一行有很多空格,需要删除# 获取第一张表格  first_table = doc.tables[0]  # 获取第一行(索引从0开始)  first_row = first_table.rows[0]  # 计算第一行中的单元格数量,即表格的列数  num_columns = len(first_row.cells)  # 打印结果  print(f"第{n}张表格有 {num_columns} 列")  # 获取第一行段落文字bt=doc.paragraphs[0].text# print(bt)# 中(5)班  第三周  活动安排LIST.append(bt[0])    # 添加年级LIST.append(bt[2])    # 添加班号if len(bt)==16:  # 一  添加周次 大写 如果长度等于15 就是一位数汉字LIST.append(bt[8:9])    elif len(bt)==18:LIST.append(bt[8:11])    # 四、五else:  # len(bt)==17 十二LIST.append(bt[8:10])# 获取第一行段落文字rq1=doc.paragraphs[1].textLIST.append(rq1[3:])    # 添加起止日期 
# print(LIST)# ll=['grade','classnum','weekhan','datelong'.]# 获取所有表格对象tables = doc.tables# 获取word中第一个表格(周计划表)table = tables[0]# 不同列的坐标数字d=[9,10,11]    # 五天 六天、七天dl=[8,9,10]        #  列数    # tj=[2,1,0]      # 添加空格数#     # print('-----提取第1张表格(周计划表)里面的内容----------')# 星期Xfor dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for xq in range(3,dl[dd]):xq1 = table.cell(0,xq).text        # K.append(k) LIST.append(xq1)for tx in range(int(tj[dd])):LIST.append('')# print(LIST)
#     # 生活名称l = table.cell(1,4).textprint(l)# 吃点心LIST.append(l)# 生活说明(1格2行,分开) (导入做参考,实际是自己写)ll=table.cell(2,4).text.split('\n')print(ll)
#    ['1.观察值日生在自主午餐环节中帮助阿姨分碗筷、毛巾的情况。', '2.提醒幼儿在自主午餐的过程中不说话,打喷嚏咳嗽要对外。']# 不要“1、”、“2、”L=[]for lll in range(2):    # 一共2条L.append(ll[lll][2:])      #    # 不要“1、”、“2、”LIST.append(ll[lll][2:])   # print(L)#     # ['观察幼儿在吃点心时是否能熟练地使用夹子夹取饼干。', '提醒个别幼儿喝完牛奶擦嘴巴。']# 运动=集体游戏+分散游戏 导入,做参考,需要调整for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for jt in range(3,dl[dd]):jt1 = table.cell(3,jt).text        # K.append(k) print(jt1)  LIST.append(jt1)for tx in range(tj[dd]):LIST.append('')# 集体游戏 for jt2 in range(3,dl[dd]):jt3 = table.cell(4,jt2).text        # K.append(k)        print(jt3)  LIST.append(jt3)for tx in range(tj[dd]):LIST.append('')# 运动观察与指导(导入做参考,实际是自己写)s=table.cell(5,4).text.split('\n')print(s)
# #     # [1.'观察幼儿是否能双手握住曲棍杆将皮球打出一定距离。', '2.观察幼儿是否能寻找皮球的多种玩法。', '3.提醒幼儿注意打曲棍干的安全。']
# #     # 有些序号是自动编号,不占字数。S=[]for sss in range(3):    # 一共3条S.append(s[sss][2:])         # 不要“1、”、“2、”、“3、”LIST.append(s[sss][2:])print(S)
#     # ['幼儿是否能双手握住曲棍杆将皮球打出一定距离。', '幼儿是否能寻找皮球的多种玩法。', '提醒幼儿注意打曲棍干的安全。']#     # 游戏内容 角色游戏 导入做参考,每年都在更换for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for fj in range(3,dl[dd]):fj2 = table.cell(7,fj).text        # K.append(k) # print(xq1)              LIST.append(fj2)for tx in range(int(tj[dd])):LIST.append('') 
#     # 游戏观察与指导(导入做参考,实际是自己写)g=table.cell(8,4).text.split('\n')print(g)# ['1、观察娃娃家的幼儿是否会照顾娃娃,与娃娃互动。', '2、重点观察医生在小医院游戏中,与病人的互动时能否加上一些肢体动作。', '3、观察幼儿角色游戏结束后,能否帮助其他伙伴一同整理材料。']# 有些序号是自动编号,不占字数。G=[]for ggg in range(2):    # 一共3条G.append(g[ggg][2:])         # 不要“1、”、“2、”、“3、”LIST.append(g[ggg][2:]) # print(G)
#     # ['观察娃娃家的幼儿是否会照顾娃娃,与娃娃互动。', '重点观察医生在小医院游戏中,与病人的互动时能否加上一些肢体动作。', '观察幼儿角色游戏结束后,能否帮助其他伙伴一同整理材料。']# 主题和主题说明ti=table.cell(9,4).text.split('\n')print(ti)# ['春天来了', '1、了解春天是个万物生长的季节,关注自然环境的不断变化。', '2、感受大自然美丽的景像,以各种方式表达自己的情感与体验。']# 有些序号是自动编号,不占字数。T=[]# 第1个春天来了,不需要删除序号,直接添加T.append(ti[0])LIST.append(ti[0])for ttt in range(1,3):    # 一共2条主题说明T.append(ti[ttt][2:])         # 不要“1、”、“2、”、LIST.append(ti[ttt][2:])print(T)# ['春天来了', '了解春天是个万物生长的季节,关注自然环境的不断变化。', '感受大自然美丽的景像,以各种方式表达自己的情感与体验。']# 个别化内容(3-5项) 一行多个,全部写入iiii=table.cell(10,4).text.split('\n')print(iiii)     LIST.append(iiii)#  ['电风扇转起来了、漂亮的帽子、绿太阳、大雨小雨、做柳树等']# 美术专用活动室ii8=table.cell(11,4).text.split('\n')print(ii8)     LIST.append(ii8)# 个别化观察与指导(导入做参考,实际是自己写)ii=table.cell(12,4).text.split('\n')# print(ii)  # # ['1.观察幼儿组装各种小电风扇的情况,鼓励幼儿不断进行尝试。', '2.观察幼儿制作帽子的情况,提示幼儿尝试不同的材料进行装饰。', '3.观察幼儿在活动过程中的专注程度,鼓励幼儿专心做自己的事。'] # # # 有些序号是自动编号,不占字数。I=[]for iii1 in range(3):    # 一共3条I.append(ii[iii1][2:])         # 不要“1、”、“2、”、“3、”LIST.append(ii[iii1][2:])print(I)# # ['观察幼儿是否能通过协商分配角色表演故事《三只蝴蝶》。', '观察幼儿是否能看懂图谱,跟着音乐打节奏。']# 集体学习 横向五个格子for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 for e in range(3,dl[dd]):k = table.cell(13,e).text        # K.append(k) LIST.append(k)for tx in range(int(tj[dd])):LIST.append('')# ['空中小屋\n(偏语言领域)', '花园里有什么\n(偏科学领域-探究)', '*猴子看猴子做\n(偏艺术领域-音乐)', '*借形想象\n(偏艺术领域-美术)', 'PATHS课程--赞美1(偏社会领域)']# 家园共育(导入做参考,实际是自己写)    yy=table.cell(14,4).text.split('\n')# print(yy)# ['1、为春游活动做准备。', '2、在家长的帮助下学习折一些纸花。', '3、天气转暖,适当地为孩子减少衣服。']# 有些序号是自动编号,不占字数。删除2字符后,可能会少前面几个字Y=[]for yyy in range(2):    # 一共3条Y.append(yy[yyy][2:])         # 不要“1、”、“2、”、“3、”LIST.append(yy[yyy][2:])print(Y)# ['为春游活动做准备。', '在家长的帮助下学习折一些纸花。', '天气转暖,适当地为孩子减少衣服。']# # 反馈与调整(因为5=7天,所以反思格子的Y不固定)for dd in range(len(d)):if num_columns==int(d[dd]):        # 分散游戏 ff=table.cell(1,dl[dd]).text.split('\n')print(ff)for j in range(2):# 提取活动1(学习活动、生活活动、游戏活动,运动)运动后面没有活动print(ff[j*4][0:4])   LIST.append(ff[j*4][0:4])    # # 提取身份1print(ff[j*4][10:-1])  LIST.append(ff[j*4][10:-1])# 提取反思1print(ff[j*4+1])LIST.append(ff[j*4+1])# print(LIST)#     # # 提取调整1print(ff[j*4+3])LIST.append(ff[j*4+3])print(LIST)print('-----提取第2-5张表格(教案)里面的内容----------')# 第1周、第20周,或国庆周会出现格子表格不满的情况,需要手动调整# 提取阿拉伯数字的周    # LIST.append(h+1)# 获取第6行段落文字,一份教案的所有教案表格上面的日期和班级都一样# word模版问题,7天的模版的教案标题在第7行,if num_columns==11:bt2=doc.paragraphs[7].textprint(bt2)# word模版问题,5天的模版的教案标题在第6行,else:bt2=doc.paragraphs[6].textprint(bt2)# 找到“期”和“第”的位置  短日期start_index = bt2.find('期')end_index = bt2.find('第')# 提取“期”到“第”之间的文字并去掉空格if start_index != -1 and end_index != -1:if start_index < end_index:date1 = bt2[start_index + 1: end_index].strip()print(date1)LIST.append(date1)    # 添加短日期# 找到“期”和“第”的位置  短日期start_index = bt2.find('(')end_index = bt2.find(')')# 提取“期”到“第”之间的文字并去掉空格if start_index != -1 and end_index != -1:if start_index < end_index:date2 = bt2[start_index + 1: end_index].strip()print(date2)LIST.append(str(date2))    # 添加添加周次# 如果是5天,就读取1-2表,如果是6天,就读取1-3条,如果是7天,就读取1-3条ts=[3,4,4]# 教案部分不足7天的格子要补成空,凑满6片 5天=4 6天=6 7天=6ks=[12,6,0]# 最后一张表(反思)的索引数for dd in range(len(d)):if num_columns==int(d[dd]):        for a in range(1,ts[dd]): # 先提取2张表(  共有3张表,其中第1、2张表提取00和01,第3表提取00)  for b in range(2):        # 表1有两个格子00 01 表2有两个格子00 01table = tables[a]        # 表1 表2 # 有两张表all=table.cell(0,b).text.split('\n')print(len(all))# 看看表格里面的行数,如果等于1行(元宵节放假),就写6个空格if len(all)==1:for tt in range(6):LIST.append('')# 看看表格里面的行数,如果大于1行,就不断写入内容else:# print(all)# 提取活动名称(删除后面的执教人员)fs1 = all[0]start_index = fs1.index(":")+1 end_index = fs1.index("执")title = fs1[start_index:end_index]                # title1 = title.replace(" ", "")LIST.append(title)         # print(title)# 空中小屋等4个题目# 提取活动目标(2行)删除前面的序号topic=[]for to in range(2,4):    # 行数mb=all[to][2:]LIST.append(mb)# topic.append(all[to][2:])# print(topic)# ['理解故事,知道春天是竹笋快速生长的季节。', '乐意想办法帮助小狐狸解决问题,并能大胆表达自己的想法。']# 提取活动准备# (第一种:经验准备)pre1=all[5][7:]LIST.append(pre1)# print(pre)# (第二种:材料准备)pre2=all[6][7:]LIST.append(pre2)# print(pre2)# ppt、故事录音# 提取活动过程pro=all[8:]PRO='\n'.join(pro)# print(PRO)LIST.append(PRO)# 一、我家住几楼---导入主题,激起幼儿兴趣# 1、你们的家住在哪里?住在几楼?为什么买这么高?# 小结:是呀,住这么高的房子可以看到远远的风景。# 2、小狐狸也想住楼房,楼上的房间高高的,远远望去,可以看见一片美景,那该多开心。# 二、房子造在哪?---分段欣赏# for tx in range(int(ks[dd])):#     LIST.append('111') for a in range(int(ts[dd]),int(ts[dd])+1): # 最后提取第3张表的00部分for b in range(1):        # 表1有两个格子00 01 表2有两个格子00 01table = tables[a]        # 表1 表2 # 有两张表all=table.cell(0,b).text.split('\n')if len(all)==1:LIST.append('')# print(all)else:# 提取活动名称(删除后面的执教人员)fs1 = all[0]start_index = fs1.index(":")+1 end_index = fs1.index("执")title = fs1[start_index:end_index]                # title1 = title.replace(" ", "")LIST.append(title)  # print(title)# 空中小屋 只有一个标题# 提取活动目标(2行)删除前面的序号topic=[]for t in range(2,4):    # 行数topic.append(all[t][2:])LIST.append(all[t][2:])# print(topic)# ['理解故事,知道春天是竹笋快速生长的季节。', '乐意想办法帮助小狐狸解决问题,并能大胆表达自己的想法。']# 提取活动准备# (第一种:经验准备)pre1=all[5][7:]LIST.append(pre1)# print(pre)# (第二种:材料准备)pre2=all[6][7:]LIST.append(pre2)# print(pre2)# 提取活动过程pro=all[8:]# print(pro)# # 这是列表样式# ['一、我家住几楼---导入主题,激起幼儿兴趣', '1、你们的家住在哪里?住在几楼?为什么买这么高?', '小结:是呀,住这么高的房子可以看到远远的风景。', '2、小狐狸也想住楼房,楼上的房间高高的,远远望去 # ,可以看见一片美景,那该多开心。', '二、房# 合并列表PRO='\n'.join(pro)# print(PRO)LIST.append(PRO)# 一、我家住几楼---导入主题,激起幼儿兴趣# 1、你们的家住在哪里?住在几楼?为什么买这么高?# 小结:是呀,住这么高的房子可以看到远远的风景。# 2、小狐狸也想住楼房,楼上的房间高高的,远远望去,可以看见一片美景,那该多开心。# 二、房子造在哪?---分段欣赏for tx in range(int(ks[dd])):if int(ks[dd])==6:# 6天3页,但是第4也第一格页要写上教案才能运行。print('tiaoguo')passelse:LIST.append('') for c in range(2):        # 表3的01有两个上下格子  表2有两个格子00 01table = tables[ts[dd]]        # 表3# 有两张表fs=table.cell(c,1).text.split('\n')# print(fs)# 提取反思的课程名字# 提取活动名称(删除后面的执教人员)fs2 = fs[1]start_index = fs2.index(":")+1 end_index = fs2.index("执")fstitle = fs2[start_index:end_index]                # title1 = title.replace(" ", "")# fstitle=fs[1][5:][:-6]# print(fstitle)LIST.append(fstitle)# 纯反思部分(第三行开始)    fs1=fs[2:]# print(fs1)fs3=[]for i in range(len(fs1)):fs4=fs1[i]        # 教案反思里手动添加四个回车# print(fs4)fs3.append(fs4)# 合并列表fs2='\n'.join(fs3)# print(fs2)LIST.append(fs2)extracted_texts = []# 遍历前5张表格for table in doc.tables[:5]:# 获取第1行单元格内容first_row_cells = table.rows[0].cells# 提取“执教:”和回车符之间的文字并去除空格for cell in first_row_cells:cell_text = cell.text.strip()if '执教:' in cell_text:start_index = cell_text.find('执教:') + len('执教:')end_index = cell_text.find('\n')extracted_text = cell_text[start_index:end_index].strip()extracted_texts.append(extracted_text)# 打印提取的文字for T in extracted_texts:print(T)    LIST.append(T)for g in range(len(LIST)):# K =[1,3,4,6,8,10]#要写入的列表的值sheet1.write(n,g,LIST[g])#写入数据参数对应 行,列,值n+=1paths2=paths+r'\09_02 新版周计划提取信息(反复多次).xls'
f.save(paths2)#保存.x1s到当前工作目录# # doc.close(path)# time.sleep(5)
# 不要删除空格了# print('--打开XLSX-,把里面的空格删除,把1、替换成1.--')# # # # 关闭Excel文件
# # workbook.close()
# import xlrd
# import xlwt# # 打开Excel文件
# workbook = xlrd.open_workbook(paths2)# worksheet = workbook.sheet_by_index(0)  # 选择要读取的工作表# # 创建一个新的Workbook对象
# new_workbook = xlwt.Workbook()
# new_worksheet = new_workbook.add_sheet('Sheet1')  # 新建一个工作表# # 遍历每一行
# for row_index in range(worksheet.nrows):
#     row_values = worksheet.row_values(row_index)
#     for col_index, cell_value in enumerate(row_values):
#         if isinstance(cell_value, str):
#             # 清除单元格内文字的格式
#             cell_value = cell_value.strip()#             # 替换文本
#             for s in range(1, 10):
#                 cell_value = cell_value.replace("{}、".format(s), "{}.".format(s))#             cell_value = cell_value.replace(' ', '')
#             cell_value = cell_value.replace(' ', '')
#             cell_value = cell_value.replace( "  ", '')#             # # 判断单元格中的文字是否有空格
#             # if ' ' in cell_value:
#             #     # 替换空格为无空格
#             #     cell_value = cell_value.replace(' ', '')#             # if ' ' in cell_value:
#             #     # 替换空格为无空格
#             #     cell_value = cell_value.replace(' ', '')#             # 替换文本
#             for s in range(1, 10):
#                 cell_value = cell_value.replace("{}、".format(s), "{}.".format(s))#         # 将修改后的值写入新的Workbook中
#         new_worksheet.write(row_index, col_index, cell_value)# # 保存修改后的Excel文件
# new_workbook.save(paths2)
# new_workbook.save(paths+r'\09_01 旧版周计划提取信息(手动修改).xls')


03-05 批量周计划(读取第二次WORD模版,并在05与09-02内部循环).py

# 一、导入相关模块,设定excel所在文件夹和生成word保存的文件夹
from docxtpl import DocxTemplate
import pandas as pd
import osprint('----1、第一次新WORD制作--------')
path = r"D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天"
print(path)file_path=path+r'\05第二次生成新WORD(循环)'
# file_path=paths+r'\06第二次生成新WORD的加粗)'# 改到教案部分,可以用加粗的进行更改
print(file_path)
os.makedirs(file_path,exist_ok=True)print('----计算每一行的数据用5天、6天还是7天的表格------')import xlrd  # 假设 path 是之前已经定义好的文件路径变量的一部分  
file_paths = path + r'\09_02 新版周计划提取信息(反复多次).xls'  
workbook = xlrd.open_workbook(file_paths)  
sheet = workbook.sheet_by_index(0)  # 获取第一张工作表    # 遍历每一行,从第二行开始(索引为1,因为索引从0开始,但Excel从1开始计数行)  
for row_idx in range(1,sheet.nrows):  # sheet.nrows 返回工作表中的行数  # 读取当前行的E到K列(列索引从0开始,但Excel列从1开始计数,所以E=4, ..., K=10)  row_data = sheet.row_values(row_idx, start_colx=4, end_colx=11)  # print(row_data)# 删除 row_data 中的空元素(None 或空字符串)  days = [cell for cell in row_data if cell is not None and cell != '']  # 统计每行非空元素的数量  (天数)day = len(days)  print(f'第{row_idx}行,本周天数是{day}天')# 如果是5天就用5天模版,如果是7天,就用7天模版tpl = DocxTemplate(path+fr'\12 周计划{day}天_横版.docx')WeeklyPlan = pd.read_excel(path+r'\09_02 新版周计划提取信息(反复多次).xls')grade = WeeklyPlan["grade"].str.rstrip()classnum =WeeklyPlan["classnum"] # 没有str.rstrip()是数字格式weekhan =WeeklyPlan["weekhan"].str.rstrip() # str.rstrip()都是文字格式# day=WeeklyPlan["day"].str.rstrip() # sc =WeeklyPlan["sc"].str.rstrip() datelong =WeeklyPlan["datelong"].str.rstrip() day1 = WeeklyPlan["day1"].str.rstrip() day2 = WeeklyPlan["day3"].str.rstrip() day3 = WeeklyPlan["day3"].str.rstrip() day4 = WeeklyPlan["day4"].str.rstrip() day5 = WeeklyPlan["day5"].str.rstrip() day6 = WeeklyPlan["day6"].str.rstrip() day7 = WeeklyPlan["day7"].str.rstrip() life = WeeklyPlan["life"].str.rstrip() life1 = WeeklyPlan["life1"].str.rstrip() life2 = WeeklyPlan["life2"].str.rstrip()sportcon1 = WeeklyPlan["sportcon1"].str.rstrip() sportcon2 = WeeklyPlan["sportcon2"].str.rstrip()sportcon3 = WeeklyPlan["sportcon3"].str.rstrip() sportcon4 = WeeklyPlan["sportcon4"].str.rstrip()sportcon5 = WeeklyPlan["sportcon5"].str.rstrip() sportcon6 = WeeklyPlan["sportcon6"].str.rstrip()sportcon7 = WeeklyPlan["sportcon7"].str.rstrip() sport1 = WeeklyPlan["sport1"].str.rstrip() sport2 = WeeklyPlan["sport2"].str.rstrip() sport3 = WeeklyPlan["sport3"].str.rstrip() sport4 = WeeklyPlan["sport4"].str.rstrip() sport5 = WeeklyPlan["sport5"].str.rstrip() sport6 = WeeklyPlan["sport6"].str.rstrip() sport7 = WeeklyPlan["sport7"].str.rstrip() sportzd1 = WeeklyPlan["sportzd1"].str.rstrip() sportzd2 = WeeklyPlan["sportzd2"].str.rstrip()sportzd3 = WeeklyPlan["sportzd3"].str.rstrip()game1 = WeeklyPlan["game1"].str.rstrip() game2 = WeeklyPlan["game2"].str.rstrip() game3 = WeeklyPlan["game3"].str.rstrip() game4 = WeeklyPlan["game4"].str.rstrip() game5 = WeeklyPlan["game5"].str.rstrip() game6 = WeeklyPlan["game6"].str.rstrip() game7 = WeeklyPlan["game7"].str.rstrip() gamezd1 = WeeklyPlan["gamezd1"].str.rstrip() gamezd2 = WeeklyPlan["gamezd2"].str.rstrip() theme= WeeklyPlan["theme"].str.rstrip() theme1= WeeklyPlan["theme1"].str.rstrip() theme2= WeeklyPlan["theme2"].str.rstrip() gbstudy = WeeklyPlan["gbstudy"].str.rstrip()art = WeeklyPlan["art"].str.rstrip()gbstudy1 = WeeklyPlan["gbstudy1"].str.rstrip() gbstudy2 = WeeklyPlan["gbstudy2"].str.rstrip() gbstudy3 = WeeklyPlan["gbstudy3"].str.rstrip() jtstudy1 = WeeklyPlan["jtstudy1"].str.rstrip() jtstudy2 = WeeklyPlan["jtstudy2"].str.rstrip() jtstudy3 = WeeklyPlan["jtstudy3"].str.rstrip() jtstudy4 = WeeklyPlan["jtstudy4"].str.rstrip() jtstudy5 = WeeklyPlan["jtstudy5"].str.rstrip() jtstudy6 = WeeklyPlan["jtstudy6"].str.rstrip() jtstudy7 = WeeklyPlan["jtstudy7"].str.rstrip() gy1 = WeeklyPlan["gy1"].str.rstrip()gy2 = WeeklyPlan["gy2"].str.rstrip()fk1	= WeeklyPlan["fk1"].str.rstrip()pj11 = WeeklyPlan["pj11"].str.rstrip()fk1nr = WeeklyPlan["fk1nr"].str.rstrip()fk1tz = WeeklyPlan["fk1tz"].str.rstrip()fk2 = WeeklyPlan["fk2"].str.rstrip()pj21= WeeklyPlan["pj21"].str.rstrip()fk2nr = WeeklyPlan["fk2nr"].str.rstrip()fk2tz = WeeklyPlan["fk2tz"].str.rstrip()dateshort=WeeklyPlan["dateshort"].str.rstrip() weekshu=WeeklyPlan["weekshu"]# 没有str.rstrip()是数字格式title1 = WeeklyPlan["title1"]# 题目后面有空格,不需要清除topic11 = WeeklyPlan["topic11"].str.rstrip()topic12 = WeeklyPlan["topic12"].str.rstrip()jy1 = WeeklyPlan["jy1"].str.rstrip()cl1 = WeeklyPlan["cl1"].str.rstrip()j1gc= WeeklyPlan["j1gc"].str.rstrip()title2 = WeeklyPlan["title2"]# 题目后面有空格,不需要清除topic21 = WeeklyPlan["topic21"].str.rstrip()topic22 = WeeklyPlan["topic22"].str.rstrip()jy2 = WeeklyPlan["jy2"].str.rstrip()cl2 = WeeklyPlan["cl2"].str.rstrip()j2gc= WeeklyPlan["j2gc"].str.rstrip()title3 = WeeklyPlan["title3"]# 题目后面有空格,不需要清除topic31 = WeeklyPlan["topic31"].str.rstrip()topic32 = WeeklyPlan["topic32"].str.rstrip()jy3 = WeeklyPlan["jy3"].str.rstrip()cl3 = WeeklyPlan["cl3"].str.rstrip()j3gc= WeeklyPlan["j3gc"].str.rstrip()title4 = WeeklyPlan["title4"]# 题目后面有空格,不需要清除topic41 = WeeklyPlan["topic41"].str.rstrip()topic42 = WeeklyPlan["topic42"].str.rstrip()jy4 = WeeklyPlan["jy4"].str.rstrip()cl4 = WeeklyPlan["cl4"].str.rstrip()j4gc= WeeklyPlan["j4gc"].str.rstrip()title5 = WeeklyPlan["title5"]# 题目后面有空格,不需要清除topic51 = WeeklyPlan["topic51"].str.rstrip()topic52 = WeeklyPlan["topic52"].str.rstrip()jy5 = WeeklyPlan["jy5"].str.rstrip()cl5 = WeeklyPlan["cl5"].str.rstrip()j5gc= WeeklyPlan["j5gc"].str.rstrip()title5 = WeeklyPlan["title5"]# 题目后面有空格,不需要清除topic51 = WeeklyPlan["topic51"].str.rstrip()topic52 = WeeklyPlan["topic52"].str.rstrip()jy5 = WeeklyPlan["jy5"].str.rstrip()cl5 = WeeklyPlan["cl5"].str.rstrip()j5gc= WeeklyPlan["j5gc"].str.rstrip()title6 = WeeklyPlan["title6"]# 题目后面有空格,不需要清除topic61 = WeeklyPlan["topic61"].str.rstrip()topic62 = WeeklyPlan["topic62"].str.rstrip()jy6 = WeeklyPlan["jy6"].str.rstrip()cl6 = WeeklyPlan["cl6"].str.rstrip()j6gc= WeeklyPlan["j6gc"].str.rstrip()title7 = WeeklyPlan["title7"]# 题目后面有空格,不需要清除topic71 = WeeklyPlan["topic71"].str.rstrip()topic72 = WeeklyPlan["topic72"].str.rstrip()jy7 = WeeklyPlan["jy7"].str.rstrip()cl7 = WeeklyPlan["cl7"].str.rstrip()j7gc= WeeklyPlan["j7gc"].str.rstrip()fs1 = WeeklyPlan["fs1"]# 题目后面有空格,不需要清除()strfs11= WeeklyPlan["fs11"].str.rstrip()fs2= WeeklyPlan["fs2"]# 题目后面有空格,不需要清除fs21= WeeklyPlan["fs21"].str.rstrip()T1 = WeeklyPlan["T1"].str.rstrip() T2 = WeeklyPlan["T2"].str.rstrip()T3 = WeeklyPlan["T3"].str.rstrip() T4 = WeeklyPlan["T4"].str.rstrip()T5 = WeeklyPlan["T5"].str.rstrip()T6 = WeeklyPlan["T6"].str.rstrip()T7 = WeeklyPlan["T7"].str.rstrip()# 遍历excel行,逐个生成# num = WeeklyPlan.shape[0]# print(num)for i in range(row_idx-1,row_idx):context = {"grade": grade[i],"classnum": classnum[i],"weekhan": weekhan[i],"datelong": datelong[i],"day1": day1[i],"day2": day2[i],"day3": day3[i], "day4": day4[i],"day5": day5[i],"day6": day4[i],"day7": day5[i],"life": life[i],"life1": life1[i],"life2": life2[i],"sportcon1": sportcon1[i],"sportcon2": sportcon2[i],"sportcon3": sportcon3[i],"sportcon4": sportcon4[i],"sportcon5": sportcon5[i],"sportcon6": sportcon6[i],"sportcon7": sportcon7[i],"weekshu": weekshu[i], "sport1": sport1[i],"sport2": sport2[i],"sport3": sport3[i], "sport4": sport4[i],"sport5": sport5[i],"sport6": sport6[i],"sport7": sport7[i],"sportzd1": sportzd1[i],  "sportzd2": sportzd2[i],"sportzd3": sportzd3[i], "game1": game1[i],"game2": game2[i],"game3": game3[i], "game4": game4[i],"game5": game5[i],"game6": game6[i],"game7": game7[i],"gamezd1": gamezd1[i],"gamezd2": gamezd2[i],"theme": theme[i],"theme1": theme1[i],"theme2": theme2[i],"gbstudy": gbstudy[i],"art": art[i],"gbstudy1": gbstudy1[i], "gbstudy2": gbstudy2[i], "gbstudy3": gbstudy3[i], "jtstudy1": jtstudy1[i],"jtstudy2": jtstudy2[i],"jtstudy3": jtstudy3[i],  "jtstudy4": jtstudy4[i],"jtstudy5": jtstudy5[i],  "jtstudy6": jtstudy6[i],"jtstudy7": jtstudy7[i],  "gy1": gy1[i],"gy2": gy2[i],"fk1": fk1[i],"pj11": pj11[i], "fk1nr": fk1nr[i],"fk1tz": fk1tz[i],"fk2": fk2[i],"pj21": pj21[i],"fk2nr": fk2nr[i],"fk2tz":fk2tz[i], "dateshort": dateshort[i],"weekshu": weekshu[i], "title1":title1[i],   "topic11":topic11[i],   "topic12":topic12[i],   "jy1":jy1[i],   "cl1":cl1[i],"j1gc": j1gc[i],"title2":title2[i],   "topic21":topic21[i],   "topic22":topic22[i],   "jy2":jy2[i],   "cl2":cl2[i],   "j2gc": j2gc[i],"title3":title3[i],   "topic31":topic31[i],   "topic32":topic32[i],   "jy3":jy3[i],   "cl3":cl3[i],   "j3gc": j3gc[i],"title4":title4[i],   "topic41":topic41[i],   "topic42":topic42[i],   "jy4":jy4[i],   "cl4":cl4[i] ,  "j4gc": j4gc[i],"title5":title5[i],   "topic51":topic51[i],   "topic52":topic52[i],   "jy5":jy5[i],   "cl5":cl5[i]  ,"j5gc": j5gc[i],"title6":title6[i],   "topic61":topic61[i],   "topic62":topic62[i],   "jy6":jy6[i],   "cl6":cl6[i]  ,"j6gc": j6gc[i],"title7":title7[i],   "topic71":topic71[i],   "topic72":topic72[i],   "jy7":jy7[i],   "cl7":cl7[i]  ,"j7gc": j7gc[i],"fs1": fs1[i],"fs11": fs11[i],"fs2": fs2[i],"fs21": fs21[i]	,"T1": T1[i],  "T2": T2[i],	"T3": T3[i],  "T4": T4[i],"T5": T5[i],"T6": T6[i],"T7": T7[i]}        tpl.render(context)  # 假设 weekshu[i] 是类似于 '4、5' 或 '7' 这样的字符串if isinstance(weekshu[i], str) and len(weekshu[i]) >2:  week_part1 = str(weekshu[i]).split('、')[0]  # 分割字符串并取第一部分week_number1 = int(week_part1)  # 转换为整数week_number2=week_number1+1  formatted_week_number = '%02d' % week_number1+'_'+'%02d' % week_number2         tpl.save(file_path+fr"\{formatted_week_number} 第{str(weekhan[i])}周 周计划 {theme[i]}({datelong[i]})({grade[i]}{classnum[i]}班下学期).docx")else:week_part1 = str(weekshu[i])# 分割字符串并取第一部分week_number1 = int(week_part1)  # 转换为整数            formatted_week_number = '%02d' % week_number1  tpl.save(file_path+fr"\{formatted_week_number} 第{str(weekhan[i])}周 周计划 {theme[i]}({datelong[i]})({grade[i]}{classnum[i]}班下学期).docx")


05-01批量周计划(教案部分三词加粗).py

'''
docx教案的表格里的“重点提问”“过渡语”“小结”加粗
(使用【办公类-22-05】周计划系列(5)-Word关键词加粗(把所有“小结”“提问”的文字设置 的代码)
作者:VBA-守候、阿夏补充
时间:2024年3月14日
'''
import os,time
from docx import Document
from docx.enum.text import WD_BREAK
from docx.oxml.ns import nsdeclsfrom docx.oxml import OxmlElement
from docx.oxml.ns import qn# 文件夹路
path=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'from win32com.client.gencache import EnsureDispatch
from win32com.client import constants # 导入枚举常数模块old_word=['提问','小结','重点重点','过渡语']
new_word=['重点提问','小结','重点','过渡语']print('-----第1步:把《04合成新周计划》里的资料复制到《06加粗测试)》-----')
#coding=utf-8
import os
import shutil# old_path = path+r'\04合成新周计划'  # 要复制的文件所在目录
old_path = path+r'\05第二次生成新WORD(循环)'  # 要复制的文件所在目录new_path = path+r'\06第二次生成新WORD的加粗'  #新路径
os.makedirs(new_path,exist_ok=True)def FindFile(path):for ipath in os.listdir(path):fulldir = os.path.join(path, ipath)  # 拼接成绝对路径print(fulldir)         #打印相关后缀的文件路径及名称if os.path.isfile(fulldir):  # 文件,匹配->打印shutil.copy(fulldir,new_path)if os.path.isdir(fulldir):  # 目录,递归   FindFile(fulldir)FindFile(old_path)print('-----第2步:提取word路径-----')from docx import Document
import ospathall=[]
path =new_path 
for file_name in os.listdir(path):print(path+'\\'+file_name)pathall.append(path+'\\'+file_name)
print(pathall)
print(len(pathall))# 19print('------第3步:每一份word替换----')#————————————————
# 版权声明:本文为CSDN博主「VBA-守候」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
# 原文链接:https://blog.csdn.net/qq_64613735/article/details/125552847
# 部分参数修改for h in range(len(pathall)):    # 20份path=pathall[h]   wdApp = EnsureDispatch("Word.Application")# aDoc = wdApp.ActiveDocument # aDoc为当前文件# wdApp.Visible = False # 程序设置为不可见aDoc = wdApp.Documents.Open(path) # 打开已经存在的文件i = 0 # 文档里有多个几个表格for ta in aDoc.Tables: # 遍历表格,如果无需遍历,直接将ta指定为某个表格即可,如这样指定为第一个表格:ta = aDoc.Tables(1)# f为每个表格区域查找f = ta.Range.Find# 查找框参数f.ClearFormatting() # 清除原有格式f.Forward = True # 向前查找f.Format = True # 查找格式f.Wrap = constants.wdFindStop # 查找完成即停止f.MatchWildcards = True # 使用通配符,根据需要设置# f.Text = '[!^13^l::]{1,}[::]' # 查找的内容  冒号前面的 [!^13^l::]    1代表z只要替换一次,[::]代表冒号。冒号前面包括冒号需要改成加粗# f.Text = '[{}]{2,}'.format(old_word) # 查找的内容  2代表2个字小结,如果1 ,就会吧“小”开头的字全部替换为小结加粗,,提问会变成两次重点提问.但是这种写法无法用format,for w in range(len(old_word)):f.Text = '{}'.format(old_word[w]) # 旧内容重点提问# 替换框参数f.Replacement.ClearFormatting() # 清除原有格式# f.Replacement.Text = '^&' # 替换框内容f.Replacement.Text = '{}'.format(new_word[w]) # 替换框内容f.Replacement.Font.Bold = True # 替换文本设置为加粗f.Execute(Replace=constants.wdReplaceAll) # 执行,查找全部i += 1aDoc.SaveAs() # 保存并关闭文件,根据需要设置time.sleep(3)aDoc.Close() # 保存并关闭文件,根据需要设置time.sleep(3)print(f'完成,共替换了{i}个表格')


06-01循环合并版本(确认设计好以后进行三合一).py

就是把03-04、03-05、03-06合并在一起,便于循环生成


07-01 批量周计划(节日部分变成五个字)py

'''
docx教案的端午节、劳动节、清明节格子里内容清除,改为“XX节放假”
作者:AI对话大师、阿夏补充
时间:2024年4月25日日'''import os
from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
from docx.oxml import OxmlElement
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_ALIGN_VERTICAL
# from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TEXT_ORIENTATION
# from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TEXT_ORIENTATION# 指定文件夹路径
path = r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
folder_path = path + r'\06第二次生成新WORD的加粗'
new_path = path + r'\07最终次生成新WORD加粗节日'
os.makedirs(new_path, exist_ok=True)j = ['中秋节假期', '元旦节假期']# 遍历文件夹下的所有文件
for filename in os.listdir(folder_path):if filename.endswith('.docx'):doc_path = os.path.join(folder_path, filename)# 打开Word文档doc = Document(doc_path)# 遍历文档中的所有表格for table in doc.tables:# 遍历表格的所有行for row in table.rows:# 遍历行的所有单元格for cell in row.cells:# 提取第一行的文字first_row_text = cell.paragraphs[0].textfor jj in j:# 判断是否符合条件if len(first_row_text) >= 10 and first_row_text[5:10] == jj:# 清空单元格的内容cell.text = ''                           # 添加新文字并设置字体p = cell.add_paragraph(jj)# # 设置文字垂直方向为纵向# p.runs[0].alignment=WD_PARAGRAPH_ALIGNMENT.Vp.runs[0].font.name = '宋体'# p.runs[0].font.bold = Truep.runs[0].font.size = Pt(30)p.runs[0]._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')# p.runs[0].font.vertical_alignment=1#  设置文字垂直方向为纵向(通过按回车,把每个字换一行)p.runs[0].text = '\n'.join(jj)# 文字在表格里上下居中cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER# 设置单元格垂直居中 文字在表格里左右居中p.alignment = WD_ALIGN_VERTICAL.CENTER                                                 # 保存修改后的文档,保存在新文件夹中,保持原文件名不变new_doc_path = os.path.join(new_path, filename)doc.save(new_doc_path)

以下是制作宣传栏和资料用
08-01 批量周计划(网站docx to jpg).py

import os
from docx import Document
from docx.shared import Pt
from pdf2image import convert_from_path
import shutilpath=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
old=path+r'\07最终次生成新WORD加粗节日'
new=path+r'\08园园通网站上传jpg(图片第一页)'
os.makedirs(new,exist_ok=True)
# 处理.docx文件from docx import Document
import osprint('--------1、遍历把周计划docx删掉反思内容,另存到jpg上传文件夹---------')
folder_path = old
for file_name in os.listdir(folder_path):print(file_name)if file_name.endswith('.docx'):file_path = os.path.join(folder_path, file_name)doc = Document(file_path)table = doc.tables[0]  # 假设第一页只有一个表格cell = table.cell(1, 8)  # 获取第1行第8列的单元格cell.text = ''  # 清空单元格内容doc.save(new+r'\{}'.format(file_name))print('--------2、打开docx文件并转换成pdf文件---------')
from docx import Document
from docx2pdf import convert
import os,timefolder_path = new
for file_name in os.listdir(folder_path):if file_name.endswith('.docx'):file_path = os.path.join(folder_path, file_name)pdf_path = file_path.replace('.docx', '.pdf')        # 打开docx文件并转换成pdf文件convert(file_path, pdf_path)time.sleep(1)print('--------3、把PDF保存为png图片---------')
import fitz  # PyMuPDF
from PIL import Image# 遍历123文件夹下的所有.pdf文件
folder_path = new
for file_name in os.listdir(folder_path):if file_name.endswith('.pdf'):file_path = os.path.join(folder_path, file_name)# 打开PDF文件pdf_document = fitz.open(file_path)# 逐页将PDF文件转换为PNG图片for page_num in range(pdf_document.page_count):page = pdf_document[page_num]image_list = page.get_pixmap()# 保存为PNG图片image = Image.frombytes("RGB", [image_list.width, image_list.height], image_list.samples)image.save(f"{os.path.splitext(file_path)[0]}{page_num+1}.png")pdf_document.close()print('--------4、删除123文件夹下的所有.docx、.pdf和.png文件,如果png文件名称最后是1. png需要保留。---------')
import osfolder_path = new
files_to_keep = set()  # 用于存储需要保留的文件名# 遍历123文件夹下的所有文件
for file_name in os.listdir(folder_path):file_path = os.path.join(folder_path, file_name)if file_name.endswith('.png') and not file_name.endswith('1.png'):os.remove(file_path)  # 删除不符合条件的.png文件elif file_name.endswith('.png'):files_to_keep.add(file_path)  # 将符合条件的文件路径加入到files_to_keep中elif file_name.endswith('.docx') or file_name.endswith('.pdf'):os.remove(file_path)  # 删除.docx和.pdf文件


08-02 批量周计划(贴墙docx删除第2-4页批量做成打印PDF).py

'''周计划第一页的合并打印(docx删除第1页反思,删除第2-4页所有内容,转为PDF,19份PDF合并打印PDF)
作者:阿夏:
时间:2024年3月18日
'''# 19个docx合并成一个PDF,便于打印import os
from docx2pdf import convert
from PyPDF2 import PdfMerger
from docx import Documentpath=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
old=path+r'\07最终次生成新WORD加粗节日'
new=path+r'\09贴墙图片PDF打印(第一页反思空)'
os.makedirs(new,exist_ok=True)new_ls=new+r'\零时文件夹'
# 检查文件夹是否存在
if not os.path.exists(new_ls):# 如果文件夹不存在,则新建文件夹os.makedirs(new_ls)# 获取docx文件列表
docx_files = os.listdir(old)
docx_files = [f for f in docx_files if f.lower().endswith('.docx')]
docx_files = docx_files[:]  # 只处理前10个docx文件# 处理.docx文件import time
from docx import Document
from docx.shared import Pt
from docx.enum.section import WD_ORIENT
from docx.shared import Cmprint('--------1、遍历把周计划docx删掉反思内容,另存到jpg上传文件夹---------')
folder_path = old
for file_name in os.listdir(folder_path):print(file_name)if file_name.endswith('.docx'):file_path = os.path.join(folder_path, file_name)doc = Document(file_path)# # 删除第0张表格里反思格子里的内容# table = doc.tables[0]  # 假设第一页只有一个表格# cell = table.cell(1, 8)  # 获取第1行第8列的单元格# cell.text = ''  # 清空单元格内容# 找到第一个分节符(分页符)后的位置start_index = 3        # 第1、2行 第3行内容保留(都是第一页上的段落文字for i, paragraph in enumerate(doc.paragraphs):if paragraph.runs:if paragraph.runs[0].text == '\x0c':  # 分页符的Unicode码为'\x0c'start_index = i + 1break# 删除第一个分节符后的段落,标题日期,这是教案表格还在的for i in range(start_index, len(doc.paragraphs)):for run in doc.paragraphs[i].runs:run.text = ''# 删除教案表格2-5。删除后会有4个空行tables = doc.tables[1:]        # 表格0是周计划,1-3是教案表格,需要删除for table in tables:table._element.getparent().remove(table._element)# 删除表格后,会有4个段落空行,把空行删除for paragraph in doc.paragraphs:if not paragraph.text.strip():  # 如果段落是空行# 删除空行p = paragraph._elementp.getparent().remove(p)# 这是只有一页周计划了,但是显示是竖版的,需要改成横版section = doc.sections[0]# 设置页面方向为横版section.orientation = WD_ORIENT.LANDSCAPE# 设置页面的宽度和高度section.page_width = Cm(29.7)  # 设置页面宽度,842磅为A4纸宽度section.page_height =Cm(21.0)  # 设置页面高度,595磅为A4纸高度# 设置页面边距为上下左右各1厘米section.top_margin = Cm(1)section.bottom_margin = Cm(1)section.left_margin = Cm(1)section.right_margin = Cm(1)# 保存新的Word文档doc.save(new_ls+r'\{}'.format(file_name))time.sleep(1)# # 将零时文件夹docx文件转换为PDF
pdf_files = []
for ls_name in os.listdir(new_ls):print(ls_name)if ls_name.endswith('.docx'):# docx_path = os.path.join(new_ls, ls_name)pdf_file = ls_name[:-5] + '.pdf'pdf_path = os.path.join(new_ls, pdf_file)convert(docx_path, pdf_path)time.sleep(1)pdf_files.append(pdf_path)# 合并PDF文件
merger = PdfMerger()
for pdf_file in pdf_files:merger.append(pdf_file)# 保存合并后的PDF文件
output_file = os.path.join(new, '(打印)2024年9月周计划合并版.pdf')
merger.write(output_file)
merger.close()print('合并完毕,结果保存在{}'.format(output_file))import shutil
# 删除临时文件夹    
shutil.rmtree(new_ls)


08-03批量周计划(年终打印期末打印_节日docx批量生成2空白PDF).py

'''周计划+教案 所有页合并打印(学期末周计划打印)。5天加1+1空白页,7天加1+0空白页时间:2024年4月26日
'''# 19个docx合并成一个PDF,便于打印import os
from docx2pdf import convert
from PyPDF2 import PdfMerger
from docx import Document
# from docx.enum.text import WD_BREAKpath=r'D:\test\02办公类\91周计划4份_20240901中2班\04 周计划7天'
old=path+r'\07最终次生成新WORD加粗节日'
new=path+r'\10期末资料PDF打印(所有内容+空白页)'
os.makedirs(new,exist_ok=True)
new_ls=new+r'\零时文件夹'
if not os.path.exists(new_ls):# 如果文件夹不存在,则新建文件夹os.makedirs(new_ls)# 获取docx文件列表
docx_files = os.listdir(old)
docx_files = [f for f in docx_files if f.lower().endswith('.docx')]
docx_files = docx_files[:]  # 只处理前10个docx文件# 处理.docx文件import time
from docx import Document
from docx.shared import Pt
from docx.enum.section import WD_ORIENT
from docx.shared import Cm
from docx.enum.section import WD_SECTION
from docx.oxml import OxmlElement
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_BREAK
from docx import Document
from docx.enum.text import WD_BREAKprint('--------1、遍历把周计划docx删掉反思内容,另存到jpg上传文件夹---------')
n=1
folder_path = old
for file_name in os.listdir(folder_path):print(file_name)if file_name.endswith('.docx'):file_path = os.path.join(folder_path, file_name)doc = Document(file_path)# 了解表格的列数和段落数量# 获取第一张表格  first_table = doc.tables[0]  # 获取第一行(索引从0开始)  first_row = first_table.rows[0]  # 计算第一行中的单元格数量,即表格的列数  num_columns = len(first_row.cells)  # 打印结果  print(f"第{n}张表格有 {num_columns} 列")  n+=1# 获取段落数量paragraph_count = len(doc.paragraphs)print(f"文档中有 {paragraph_count} 个段落")# 在第三段前插入一个分页符(保证第二页是空白,打印时可以第一面是横版周计划,第二页是空白)#   获取所有段落paragraphs = doc.paragraphs# 确保文档至少有3段if len(paragraphs) >= 4:# 获取第3段third_paragraph = paragraphs[3]# 在第三段的最前面插入一个换页符run = third_paragraph.insert_paragraph_before().add_run()run.add_break(WD_BREAK.PAGE)else:print("文档少于3段")#  # 设置页边距(横版和竖版的页边距不同,所以这里不设置)# sections = doc.sections# for section in sections:#     section.page_width = Cm(21)  # 设置页面宽度为21厘米#     section.page_height = Cm(29.7)  # 设置页面高度为29.7厘米#     section.left_margin = Cm(3)  # 设置左页边距为3厘米#     section.right_margin = Cm(3)  # 设置右页边距为3厘米#     section.top_margin = Cm(2)  # 设置上页边距为2厘米#     section.bottom_margin = Cm(2)  # 设置下页边距为2厘米# 获取文档中的所有节,如果6天和7天,最后不要一页空白,如果是5天,就要插入一页空白sections = doc.sectionslast_section = sectionsif num_columns==9:for _ in range(1): # 插入两次回车# 在最后一个节后面插入一个新的节new_section = doc.add_section(WD_SECTION.NEW_PAGE)if num_columns==10:            passif num_columns==11:            pass# 在最后一个节后面插入一个新的节# # 在最后一个节后面插入一个新的节# new_section = doc.add_section(WD_SECTION.NEW_PAGE)doc.save(new_ls+r'\{}'.format(file_name))time.sleep(1)# # 将零时文件夹docx文件转换为PDF
pdf_files = []
for ls_name in os.listdir(new_ls):print(ls_name)if ls_name.endswith('.docx'):# docx_path = os.path.join(new_ls, ls_name)pdf_file = ls_name[:-5] + '.pdf'pdf_path = os.path.join(new_ls, pdf_file)convert(docx_path, pdf_path)time.sleep(1)pdf_files.append(pdf_path)# 合并PDF文件
merger = PdfMerger()
for pdf_file in pdf_files:merger.append(pdf_file)# 保存合并后的PDF文件
output_file = os.path.join(new, '(打印)2024年9月周计划教案合并版(双面打印专用).pdf')
merger.write(output_file)
merger.close()print('合并完毕,结果保存在{}'.format(output_file))import shutil
# 删除临时文件夹    
shutil.rmtree(new_ls)


08-04(备用)提取EXCEL第行的名称都是字母.py(制作EXCEL的标题栏用)

import xlrd# 打开Excel文件
workbook = xlrd.open_workbook(r'D:\test\02办公类\91周计划4份_2024年中2班\04 周计划\09 原计划提取的内容.xlsx')# 获取第一个表格
worksheet = workbook.sheet_by_index(0)# 读取第一行的所有列的内容,并写入列表
data = []
for col in range(worksheet.ncols):cell_value = worksheet.cell_value(0, col)data.append(cell_value)print(data)

感悟:

太复杂了,已经说不清楚,只适合我自己的word模板模版使用。每学期调试就要2-3天,还有大量的时间用来补全反思文字

但是写完后,面对动不动就要调整教案格式内容的资料要求(检查时、期末资料时、专家指点时),它能快速批量最终生成一大套资料,那时就感觉Python太实用了。


http://www.mrgr.cn/news/59975.html

相关文章:

  • UML之用例视图
  • 深入理解JAVA虚拟机(一)
  • python笔记一
  • 用哪种建站程序做谷歌SEO更容易?
  • Spring Cache-基于注解的缓存
  • Mysql入门3——多表操作、事务、索引
  • vue3 debounce 作用:函数会从其被调用时延迟执行到调用结束的这段时间内,如果该函数被再次调用,则重新计算时间。
  • 使用 BERT 和逻辑回归进行文本分类及示例验证
  • 在数据库访问中,使用localhost、127.0.0.1和IP地址有什么差异
  • Java 中的 队列(Queue)与双端队列(Deque)
  • Host Key Verification Failed
  • 软件测试学习总结
  • 【Python】为Pandas加速(适合Pandas中级开发者)
  • PG数据库之数据类型入门
  • 【mysql】什么是当前读
  • JMeter 接口和性能测试常用函数最全解析!
  • ICP之点云特征计算
  • 只需要写几行 SQL,这个网站就搭好了?
  • shell脚本每日一练4
  • GitHub 上传项目保姆级教程
  • 【C++单调栈 贡献法】907. 子数组的最小值之和|1975
  • python基于django线上视频学习系统设计与实现_j0189d4x
  • 【Linux系统编程】——Linux入门指南:从零开始掌握操作系统的核心(指令篇)
  • 基于SpringBoot的中药材进存销管理系统设计与实现
  • 在浏览器中运行 Puppeteer:解锁新能力
  • React 中组件通信的几种主要方式