背景需求:
1-4月电子屏表格,都是用这个代码将EXCEL数据整理成分类成3个WORD表格。
【办公类-48-04】20250118每月电子屏台账汇总成docx-4(提取EXCLE里面1月份的内容,自制月份文件夹)-CSDN博客文章浏览阅读1.2k次,点赞29次,收藏9次。【办公类-48-04】20250118每月电子屏台账汇总成docx-4(提取EXCLE里面1月份的内容,自制月份文件夹)https://blog.csdn.net/reasonsummer/article/details/145230274?spm=1011.2415.3001.5331
存在问题:
每月都要把下载EXCEL名称复制到代码内,有点麻烦。
我希望只要把EXCEL放到文件夹下,程序就能自动转移到2025年5月文件夹内。并识别它做三个WORD表格
deepseek的答案
20250603,获取5月的所有EXCEL,导出文本EXCEL
放到一级文件夹下
然后用代码慢慢生成
'''
电子屏台账2025年5月,自动提取当月内容(在XX之间的内容),制作当月文件夹
把EXCEL放在一级文件夹下,自动读取它并转移到2025年5月文件夹
自动识别2025年5月文件夹内的EXCEL,开始制作三个园区台账WORD,并打包rar
作者:星火讯飞、deepseek、阿夏
时间:20240603
'''
print('----1、读取EXCEL内容并合并成关键列表------')
import os
import shutil
import pandas as pd
path= r'C:\Users\jg2yXRZ\OneDrive\桌面\电子屏每月2024'
year=2025
# int(input('几年(2025?\n'))
month=int(input('几月?(4)\n'))
garden=['总园', '一分园','二分园']
folder_path = path+fr"\{year}年{month:02}月"
os.makedirs(folder_path,exist_ok=True)
folder_name=folder_path+fr'\(以此为准){year}年{month:02}月电子屏台账(三个园区)'
os.makedirs(folder_name,exist_ok=True)
# 把EXCLe复制到2025年1月文件夹
file_name = '279855026_20240901Jg2y各园部重点部位电子屏、播控系统_956f958e-4232-47d7-a6bb-2c086e4ade44.xlsx'
# 把问卷星下载的xlsx转移到2025年1月文件夹内
# 定义源文件和目标文件夹路径
src_file = path+fr'\{file_name}'
dst_folder = folder_path
dst_file = os.path.join(dst_folder, f'{file_name}')
# 移动文件到目标文件夹
shutil.move(src_file, dst_file)
# 279855026_按文本_20240901Jg2y各园部重点部位电子屏、播控系统_83_83.xlsx'
file_path = os.path.join(folder_path, file_name)
print(file_path)
# 按行读取
df = pd.read_excel(file_path)
filtered_rows = df.iloc[:, 6:22].values.tolist() # G列到W列的数据,按行转换为列表
# print(rows)
# 提取符合的日期
print('----1、初始化一个空列表来存储符合条件的行(数字是01的月份)------')
#
rows = []
# 遍历每一行
for row in filtered_rows:
# 获取第9个元素(索引从0开始,所以是14)
cell_value = str(row[9])
# print(cell_value)
# 检查第5-6个字符是否为“01”
if cell_value[5:7] == f"{month:02}":
rows.append(row)
# # 打印符合条件的行
print(rows)
for x in range(len(garden)):
all_data=[]
for y in range(len(rows)):
if rows[y][0][2:]==garden[x]:
# print(rows[y])
for row in rows[y][1:]:
# print(row)
if row=='(跳过)':
pass
else:
all_data.append(row)
# print(all_data)
# print(len(all_data))
# 462
print('----1、读取EXCEL内容并合并成关键列表------')
import pandas as pd
# # 每行有几个内容
h=7
# print(h)
# # 拆分成7个一组
nested_lists = [all_data[i:i+h] for i in range(0, len(all_data), h)]
# print(nested_lists)
# print(len(nested_lists))
# # # 26
# 如果条数不满20条,只有一页
if len(nested_lists) <=20:
print(f"{len(nested_lists)} 在范围 0-20 内")
kong = 20 - len(nested_lists)
print(kong)
Y = 1
# 判断多页情况下,最后一页是否能够凑满20行,凑不满,补空
else:
for z in range(20, 220, 20):
if z < len(nested_lists) <= z + 20:
# 出现过正好40条,只有两页,但出现了第3空页,少了小于等于z+2-
print(f"{len(nested_lists)} 在范围 {z}-{z+20} 内")
# 补多少的空格
kong = z + 20 - len(nested_lists)
print(kong)
# 有几页
Y = int((z + 20) / 20)
# 一个列表里面有7个空
w = [''] * h
# 需要14个这种7空的嵌套列表
v = [w] * kong
# print(v)
# 把实际的填写内容+补充的空格,凑满20的倍数页
nested_lists=nested_lists+v
# print(nested_lists)
# print(len(nested_lists))
# 80
# 拆分合并每个格子的内容
new=[]
for n in range(len(nested_lists)): # 66行
# 如果读取的第一个内容为空
if nested_lists[n][1]=='':
for g in range(h):
new.append('')
else:
# 添加序号不用加0
new.append(n+1)
# 电子屏ID '总园 校门口电子屏 402XXXXXXXX TY2021XXXXXX'
split_list = nested_lists[n][1].split(' ')
# print(split_list)
# 将空格切开变成列表
new.append(split_list[2])
# 资产编号
new.append(split_list[3])
# 时间 (日期+时间
new.append(nested_lists[n][2][:4]+'年'+nested_lists[n][2][5:7]+'月'+ \
nested_lists[n][2][-2:]+'日'+str(nested_lists[n][3])+':'+str('%02d'%nested_lists[n][4]))
# 操作内容
new.append(nested_lists[n][5])
# 进出人员 (负责人)
new.append(nested_lists[n][0])
# 审核领导(园所管理主任)
new.append(nested_lists[n][6])
print(new)
print(len(new))
# 560 /7/20=4页
print('----2、读取docx模板的数量------')
# 读取word的行列数
from docx import Document
doc_name = '电子屏台账模板.docx'
doc_path = os.path.join(path, doc_name)
# 打开文档
doc = Document(doc_path)
# 获取第一个表格
table = doc.tables[0]
# 获取表格的行数和列数
num_rows = len(table.rows)
num_cols = len(table.columns)
# print("行数:", num_rows)
# # 22
# print("列数:", num_cols)
# 7
# 每页格子的坐标
bg=[]
for a in range(2,22):
for b in range(7):
bg.append('{}{}'.format('%02d'%a,'%02d'%b))
# print(bg)
# print(len(bg))
# 140
# 拆分成4页每页20个个一组
c=int(len(new)/Y)
content_lists = [new[i:i+c] for i in range(0, len(new), c)]
# print(content_lists)
# print(len(content_lists))
# 15
# 4 拆20行内容一组,一共4个嵌套列表
# 列表new内容写入docx模板,第一页写入20行*7的内容
import os,time
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx2pdf import convert
from PyPDF2 import PdfMerger
# 多少份(必须双数)
ziti = '宋体'
size = 14
imagePath = folder_path+r'\零时Word'
if not os.path.exists(imagePath):
os.makedirs(imagePath)
for n in range(len(content_lists)):
doc = Document(doc_path)
# for b in range(0):
table = doc.tables[0]
for t in range(len(bg)):
pp, qq, k = int(bg[t][0:2]), int(bg[t][2:4]), content_lists[n][t]
run = table.cell(pp, qq).paragraphs[0].add_run(str(k))
run.font.name = ziti
run.font.size = Pt(size)
run.bold = False
run.font.color.rgb = RGBColor(0, 0, 0)
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), ziti)
table.cell(pp, qq).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
doc.save(imagePath+fr'\{n:02d}.docx')
time.sleep(2)
print('-----3、创建一个带页码的docx,合并word模板------')
from docx import Document
from docx.enum.section import WD_SECTION_START
import os
from docx.shared import Cm
# # 创建一个带页码的空Document对象,并把页眉页脚边距改小
source_dir = imagePath # 文件夹路径
combined_doc = Document(path+r'\页码.docx')
# 读取“整理”里面的docx的内容
docx_files = []
for file_name in os.listdir(source_dir):
if file_name.endswith(".docx"):
docx_files.append(os.path.join(source_dir, file_name))
for file in docx_files:
doc = Document(file)
for element in doc.element.body:
combined_doc.element.body.append(element)
output_file = folder_name + fr'\{year}年{month:02}月({garden[x]})电子屏台账.docx' # 输出文件路径
output_file1 = folder_name + fr'\{year}年{month:02}月({garden[x]})电子屏台账2.docx' # 输出文件路径
combined_doc.save(output_file)
time.sleep(2)
print('-----4、把“合并docx"的第一段回车删除。(页码模板自带)---')
doc = Document(output_file)
# 删除第1个段落(都只有一个回车)
for i in [0]:
dell_paragraph = doc.paragraphs[i]
doc._element.body.remove(dell_paragraph._element)
# 保存文档
doc.save(output_file)
# time.sleep(2)
print('-----5、替换园区---')
import win32com.client as win32
# 创建Word应用程序对象
word_app = win32.gencache.EnsureDispatch("Word.Application")
# 打开Word文档
doc = word_app.Documents.Open(output_file)
# 创建Find对象
find_object = doc.Content.Find
# 设置查找和替换参数
find_object.Text = "园区"
find_object.Replacement.Text = garden[x]
find_object.Forward = True
find_object.Wrap = 1
find_object.Format = False
find_object.MatchCase = False
find_object.MatchWholeWord = False
find_object.MatchWildcards = False
find_object.MatchSoundsLike = False
find_object.MatchAllWordForms = False
# 执行查找和替换
find_object.Execute(Replace=2)
# 保存文档
doc.SaveAs(output_file)
# 关闭文档和应用程序
doc.Close()
word_app.Quit()
time.sleep(2)
# 删除word临时文件夹
import shutil
shutil.rmtree(imagePath)
# 定义要打包的文件夹名称
shutil.make_archive(folder_name, 'zip', folder_name)