【办公类-22-08】周计划系列(4)“育儿知识(家园小报)“ (2024年调整版本)

本文描述了一位技术专家如何使用Python自动化处理“家园小报”文档,包括文件名格式调整、doc转docx、清理文本框内容、手动提取Excel数据填充word模板、生成多份文档以及将内容转为png格式,以提高工作效率。
摘要由CSDN通过智能技术生成

作品展示

背景需求:

制作“育儿知识(家园小报)”,查询发现去年就没有做

因为“家园小报”基本没有段落文字,都是“文本框文字、艺术字“,很难用python提取文字。

由于只有6篇,因此去年采用的就是手动贴文字到excel表格中,再用word模板批量的方法

今年尝试用python读取word文本框文字,还是显示为空,

所以和去年一样,手动复制word,制作excel内容.

本学年墙面贴的是“育儿知识”A4竖版

将两份代码合并

主要步骤:

1、doc更改,统一文件名长度

2、doc转docx

3、docx去掉回车符(空行)发现内部都是文本框,清除回车后整个文本框都删光了

4、手动提取word内容导入EXCEL

5、在word模板里,将EXCEL内容填入,保存多个docx

6、把docx转成png

6、把1张png切割成2张png(班级主页)

素材准备:

都是“03 育儿知识 ”下的内容

第01步:修改文件名 

把文件名改成”2024年02月 家园小报.doc“

代码展示:

微调部分——统计文件名的长度:

import os
import time


path =r"D:\test\02办公类\91周计划4份_2024年中4班\03 育儿知识\01doc"

fileList=os.listdir(path)

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='2024年'+newname1+'月 家园小报.doc'
  oldname_path = os.path.join(path,file)
  # 文件新路径
  newname_path = os.path.join(path,newname)
  # 新旧对调
  os.rename(oldname_path, newname_path)

#  2023年2周 家园小报.doc 16字符

# 延时
time.sleep(2)

fileList=os.listdir(path)

for file in fileList:   

  if len(file)==16:    #2023年2周 家园小报.doc 16字符   16是一位数的周次 
    print(file)   
    split_str = file.split('年')
    newname1 = split_str[0]  # _的第0部分=序号 
    print(newname1)
    newname2= split_str[1]  # _的第0部分=序号 
    print(newname2)
    newname=newname1+'年0'+newname2
    oldname_path = os.path.join(path,file)
    # 文件新路径
    newname_path = os.path.join(path,newname)
    # 新旧对调
    os.rename(oldname_path, newname_path)

  if len(file)==17:     # 2023年12周 家园小报.doc 16字符  17是两位数的周次    
    pass
  

终端显示

第2步:原有文件格式从doc变成docx

代码展示——doc文件下的19个doc转到docx文件下的19个docx

import os
from win32com import client as wc
import time
#  注意:目录的格式必须写成双反斜杠
path=r"D:\test\02办公类\91周计划4份_2024年中4班\03 育儿知识"
oldpath=path+r'\01doc'  # 使用绝对地址(可更改)原文件doc地址
newpath=path+r'\02docx'# 使用绝对地址(可更改)docx地址

# 提取所有doc内的19周doc周计划的路径
files=[]
for file in os.listdir(oldpath):
    # 找出文件中以.doc结尾并且不以~$开头的文件(~$是为了排除临时文件)
    if file.endswith('.doc') and not file.startswith('~$'): 
        files.append(oldpath+'\\'+file)
        print(files)

# 打开doc文件下的doc文件,另存到docx文件下的docx文件
for file in files:
    word = wc.Dispatch("Word.Application")
    print("已处理文件:"+file)
# #     # 打开文件
    doc = word.Documents.Open(file)
#     # # 将文件另存为到docx文件夹,另存为.docx

#   # 这里根据文件名称长度,进行数字确定
    # 2023年06周 家园小报.doc 一共17字符
    new=newpath+'\\'+file[-17:]+'x'
    print(new)
    doc.SaveAs("{}".format(new), 12)    # 12表示docx格式
    doc.Close()

           
 
 

第3步:删除docx里面的回车符

删除回车符,就把原来的“家园小报”里面所有的文本框都删掉了,

这里先跳过。

第4步:整理“主题知识”的EXCEL信息,手动写入 中4班下学期“主题知识”.xlsx

打开每一个word

选取标题和内容(每页上有2套)

同样方法复制所有文本框里的内容。

EXCEL里面有特殊格式 空格,顿号、可以用程序批量删除,修改

代码展示:

# https://blog.csdn.net/lau_jw/article/details/114383781

from docx import Document
from openpyxl import load_workbook
import glob
import re
 
#  将模板 Excel 读取进程序:
path = r"D:\test\02办公类\91周计划4份_2024年中4班\03 育儿知识"
workbook = load_workbook(path + r'\10 改周次过渡模板_育儿知识.xlsx')
sheet = workbook.active

# 手动贴入信息

print('--打开XLSX-,把里面的空格删除,把1、替换成1.--')# 
# 打开Excel文件
workbook = load_workbook(path + r'\11 中4班下学期_育儿知识.xlsx')
# 获取第一个工作表
worksheet = workbook.active

# # 遍历每个单元格
for row in worksheet.iter_rows():
    
    for cell in row:        
        if cell.value and isinstance(cell.value, str):            
            # 清除单元格内文字的格式
            cell.value = cell.value.strip()
            

        # 判断单元格中的文字是否有空格
        if ' ' in str(cell.value):
            # 替换空格为无空格
            cell.value = str(cell.value).replace(' ', '')

        if ' ' in str(cell.value):
            # 替换空格为无空格
            cell.value = str(cell.value).replace(' ', '')

        # 替换文本
        for s in range(1,10):
            if cell.value and isinstance(cell.value, str):
                cell.value = cell.value.replace("{}、".format(s), "{}.".format(s))

# 保存修改后的Excel文件
workbook.save(path + r'\11 中4班下学期_育儿知识.xlsx')

# 关闭Excel文件
workbook.close()

# number = 0

#  # 提取四个加粗标题所在的行数    # 参考https://www.shouxicto.com/article/96876.html

# for file in glob.glob(path + r'\03去掉回车\*.docx'):
#     print(file)

#     doc= Document(file)

#     #获取每个文档的行数  
#     # print("段落数:"+str(len(doc.paragraphs)))#段落数为13,每个回车隔离一段
#     d=len(doc.paragraphs)

#         # 保存所有段落文字的列表
#         # 保存所有段落文字的列表
#     paragraphs = []

#     # # 遍历文档中的段落,并将文字添加到列表中
#     # for paragraph in doc.paragraphs:
#     #     paragraphs.append(paragraph.text)

#     # # 遍历文档中的内联形状,提取文本框文字并添加到列表中
#     # for shape in doc.inline_shapes:
#     #     if shape.text_frame:
#     #         paragraphs.append(shape.text_frame.text)
#     # print(paragraphs)

#     # 提取word文本框中文本
    
#     children = file.element.body.iter()
#     child_iters = []
#     for child in children:
#         # 通过类型判断目录
#         if child.tag.endswith('textbox'):
#             for ci in child.iter():
#                 if ci.tag.endswith('main}r'):
#                     child_iters.append(ci)
#     textbox = [ci.text for ci in child_iters]
#     print(textbox)



  
# #     number += 1
# #     # sheet.append([number, content1,content2,content3,content4])  # number是序号,一共遍历提取了几分Word的内容,content是育儿知识中间部分的内容

# #     sheet.cell(row=number+1, column=1).value = number
# #     sheet.cell(row=number+1, column=2).value = content1
# #     sheet.cell(row=number+1, column=3).value = content2
# #     sheet.cell(row=number+1, column=4).value = content3
# #     sheet.cell(row=number+1, column=5).value = content4
 
# # workbook.save(path + r'\11 中4班下学期_育儿知识.xlsx')
# # workbook.close()


结果展示

第5步:读取word模板,把EXCEL-育儿知识 的内容 合成6份 Docx

代码展示

# 一、导入相关模块,设定excel所在文件夹和生成word保存的文件夹
from docxtpl import DocxTemplate
import pandas as pd
import os
import xlwt
import xlrd
import os
import random
from win32com.client import constants,gencache
from win32com.client.gencache import EnsureDispatch
from win32com.client import constants # 导入枚举常数模块
import os,time
import docx
from docx import Document
from docx.shared import Pt 
from docx.shared import RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT



# path=r'D:\\test\\02办公类\\90周计划4份\\06 信息窗+主题知识'+'\\'
path = r"D:\test\02办公类\91周计划4份_2024年中4班\06 信息窗+主题知识"
print(path)

file_path=path+r'\04合成新信息窗主题知识'
print(file_path)

# 二、遍历excel,逐个生成word(小标签.docx是前面的模板)
try:
    os.mkdir(file_path)
except:
    pass



list = pd.read_excel(path+'\\11 中4班下学期_信息窗主题知识.xlsx')
# 信息窗
title = list["title"].str.rstrip()
name =list["name"]
content=list["content"].str.rstrip()# 没有str.rstrip()是数字格式
classroom =list["classroom"].str.rstrip() # str.rstrip()都是文字格式
T1 =list["T1"].str.rstrip() # 没有str.rstrip()是数字格式
T2 =list["T2"].str.rstrip()# 没有str.rstrip()是数字格式
time=list["time"].str.rstrip() 

# 主题知识
titlename = list["titlename"].str.rstrip()
name1=list["name1"]
sm=list["sm"].str.rstrip()# 没有str.rstrip()是数字格式
mb=list["mb"].str.rstrip()# 没有str.rstrip()是数字格式
gy=list["gy"].str.rstrip()# 没有str.rstrip()是数字格式
classroom1 =list["classroom1"].str.rstrip() # str.rstrip()都是文字格式
# T1 =list["T1"].str.rstrip() # 没有str.rstrip()是数字格式
# T2 =list["T2"].str.rstrip()# 没有str.rstrip()是数字格式
time1=list["time1"].str.rstrip() 


# 遍历excel行,逐个生成
num = list.shape[0]
for i in range(num):
    context = {
       "title": title[i],
       "content": content[i],        
       "classroom": classroom[i],
       "name" :name[i],
       "T1": T1[i],
       "T2": T2[i],       
       "time": time[i], 

        "name1": name1[i],
        "titlename": titlename[i],
        "sm": sm[i],  
        "mb" :mb[i],
        "gy" :gy[i],      
        "classroom1": classroom1[i],       
        "time1": time1[i],          
       
    }
  
    tpl = DocxTemplate(path+'\\12 信息窗主题知识_竖版双.docx')
    # tpl = DocxTemplate(path+'\\12 信息窗主题知识_横版双.docx')
 
    tpl.render(context)
    # tpl.save(file_path+r"\\第{}周 {}班 信息窗({}).docx".format('%02d'%name[i],classroom[i],time[i]))
    tpl.save(file_path+r"\\第{}周 {}班 信息窗主题知识({}).docx".format('%02d'%name[i],classroom[i],time[i]))


   

运行结果

打开手动清除不要的内容、调整首行缩进、控制字数多少与版面样式,不需要手码日期了(*^_^*)

第6步:把育儿知识”转为png格式(a4竖版板一页)

代码展示:

'''
作者:毛毛 
性质:转载
原网址 https://zhuanlan.zhihu.com/p/367985422

安装python,确保以下模块已经安装:win32com,fitz,re
在桌面新建文件夹,命名为:word2pdf2png
将需要转换的word(只能docx格式,可以多个)放入文件夹word2pdf2png
复制以下代码并运行。

本代码只生成png 文件夹内只有一级,子文件不生成

说明:
1、
2、把“03 新周计划生成(原版)”的内容复制到“04 新周计划(没有反思的打印)”
3、把“04 新周计划(没有反思的打印)”内容复制到“05 新周计划(没有反思的jpg上传)”
4、然后“05 新周计划(没有反思的jpg上传)”文件夹删除并生成第一张无反思的图片20份
5、空余时间。把““03 新周计划生成(原版)”文件夹的内容复制到“08 新周计划生成(手动修改-准)”文件夹,手动修改
(1)周计划第一页反思(限定在一页内)
(2)教案等
'''
#coding=utf-8
from win32com.client import Dispatch
import os
import re
import fitz
wdFormatPDF = 17 #转换的类型
zoom_x=2 #尺寸大小,越大图片越清晰 5超大,这里改成2
zoom_y=2 #尺寸大小,越大图片越清晰,长宽保持一致
rotation_angle=0#旋转的角度,0为不旋转


# print(----'把"04合成新育儿知识"文件夹里的资料复制到"05jpg上传"'-----)

import os
import shutil

def copy_docx_files(source_dir, dest_dir):
    for filename in os.listdir(source_dir):
        source_path = os.path.join(source_dir, filename)
        dest_path = os.path.join(dest_dir, filename)
        
        if os.path.isfile(source_path) and filename.endswith(".docx"):
            shutil.copy(source_path, dest_path)
        
        if os.path.isdir(source_path):
            copy_docx_files(source_path, dest_dir)

# 指定源文件夹和目标文件夹
old_pat =r'D:\test\02办公类\91周计划4份_2024年中4班\03 育儿知识\04合成新育儿知识'  # 要复制的文件所在目录
new_path = r'D:\test\02办公类\91周计划4份_2024年中4班\03 育儿知识\05jpg上传'  #新路径


# 调用复制函数
copy_docx_files(old_pat, new_path)


#print(----生成PDF和第一页图片-----)
def doc2pdf2png(input_file):

    for root, dirs, files in os.walk(input_file):
        for file in files:
            if re.search('\.(docx|doc)$', file):
                filename = os.path.abspath(root + "\\" + file)
                print('filename', filename)
                word = Dispatch('Word.Application')
                doc = word.Documents.Open(filename)
                doc.SaveAs(filename.replace(".docx", ".pdf"), FileFormat=wdFormatPDF)
                doc.Close()
        word.Quit()

    for root, dirs, files in os.walk(input_file):
        for file in files:
            if re.search('\.pdf$', file):
                filename = os.path.abspath(root + "\\" + file)
                print('filename', filename)
                # 打开PDF文件
                pdf = fitz.open(filename)
                # 逐页读取PDF
                for pg in range(0, pdf.pageCount):
                    page = pdf[pg]
                    # 设置缩放和旋转系数
                    trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)
                    pm = page.getPixmap(matrix=trans, alpha=False)
                    # 开始写图像
                    pm.writePNG(filename.replace('.pdf', '') + str(pg+1) + ".png")
                pdf.close()

doc2pdf2png(new_path)

# 删除生成文件PDF  和 生成文件docx
for parent, dirnames, filenames in os.walk(new_path):
    for fn in filenames:
        if fn.lower().endswith('.pdf'):
            os.remove(os.path.join(parent, fn))
        if fn.lower().endswith('.docx'):# 删除原始文件docx 正则[pdf|docx]套不上,只能分成两条了
            os.remove(os.path.join(parent, fn))
           
# 删除png中,尾号是2-8的png(Word只要第一页,后面生成的第二页图片不要
for parent, dirnames, filenames in os.walk(new_path):
        for fn in filenames:
            for k in range(2,9):                # png文件名的尾数是2,3,4,5,6,7,8 不确定共有几页,可以把9这个数字写大一点)
                if fn.lower().endswith(f'{k}.png'):  # 删除尾号为2,3,4,5,6,7,8的png图片 f{k}='{}'.formart(k) 
                    os.remove(os.path.join(parent, fn))

图片结果展示

先出现word和PDF、最后出现一张图片

说明:由于每次选用的word原素材格式、内容、结构都不同,所以最好把代码分成6个,逐一调整路径、内容选择范围等。这是个很细致的活儿。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿夏reasonsummer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值