#制作100份word表
from docx import Document
from openpyxl import load_workbook
import os,shutil
import time
def progressBar(i,total):
print('
当前进度:{0}{1}%'.format('■'*(i+1),int((i+1)/total*100)),end='')
def delOldDir(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
def make100Word(docx_file_path,xlsx_file_path,dir_path):
if not os.path.exists(dir_path):
os.mkdir(dir_path)
#打开excel表
workbook = load_workbook(xlsx_file_path)
sheet = workbook.active
count =0
#有效信息行是从第一行开始的,第一行是表头,包含列名,也是文本替换的依据
for table_row in range(1,sheet.max_row+1):
count += 1
#每循环一行实例化一个新的word文件
wordfile = Document(docx_file_path)
#单元格需要逐个遍历,每一个都包含着有用的信息
for table_col in range(1,sheet.max_column + 1):
# 旧的文本也就是列名,已经在模板里填好了,用于文本替换,将row限定在第一行后就是列名
old_text = str(sheet.cell(row=1,column = table_col).value)
# 新的文本就是实际的信息,table_col循环到某个数值时,实际的单元格和列名就确定了
new_text=str(sheet.cell(row = table_row,column = table_col).value)
# 加上这个判断是因为日期信息读进程序是“日期 时间”格式的,如果要保留日期信息可以用字符串方法或者用time/datetime模块处理
if ' ' in new_text:
new_text = new_text.split()[0]
#单元格为空值时,会输入None,可以替换为空格
if new_text =='None':
new_text=" "
# 文档Document - 段落Paragraph - 文字块Run
all_paragraphs = wordfile.paragraphs
for paragraph in all_paragraphs:
for run in paragraph.runs:
run.text = run.text.replace(old_text,new_text)
# 文档Document - 表格Table - 行Row/列Column - 单元格Cell
all_tables = wordfile.tables
for table in all_tables:
for row in table.rows:
for cell in row.cells:
cell.text = cell.text.replace(old_text,new_text)
#获取学号姓名生成转递信息表的名称
if (table_row >1):
num = str(sheet.cell(row=table_row,column=1).value)
sno = str(sheet.cell(row=table_row,column=2).value)
sname =str(sheet.cell(row=table_row,column=3).value)
save_file_name = num + "#" + sno + "#" +sname +"_档案转递信息.docx"
wordfile.save(dir_path +"/"+save_file_name)
#打印进度
progressBar(count,sheet.max_row+1)
return (count-1)
def takeTime(start_time):
seconds = time.time()-start_time
return seconds
def main():
start_time = time.time()
root = os.getcwd() + "/"
dir_path = root + "转递信息"
docx_file_path = root + '转寄信息模板.docx'
xlsx_file_path = root + 'dataSource.xlsx'
delOldDir(dir_path)
count = make100Word(docx_file_path,xlsx_file_path,dir_path)
print("
成功生成{0}个word文档,耗时{1:.1f}秒。
保存路径:{2}".format(
count,takeTime(start_time),dir_path))
#打开保存路径
os.startfile(dir_path)
input("按任意键退出……")
main()