from openpyxl import load_workbook
from docx import Document
# 打开Excel文件
workbook = load_workbook('data.xlsx')
# 选择要读取的工作表
worksheet = workbook['Sheet1']
# 获取每个科目的列索引
subjects = ['语文', '数学', '英语']
subject_columns = {}
for col in range(2, 5):
subject_columns[worksheet.cell(row=1, column=col).value] = col #检索到的值用作字典中的关键字,相应的列编号用作值
# 打开Word文档模板
template_document = Document('template.docx')
# 遍历每一行,总结每个学生的学习情况
for row in worksheet.iter_rows(min_row=2, values_only=True): #从第二行开始,values_only=True表示返回对应的值,FALSE表示返回的对象
student_name = row[0]
scores = row[1:]
scores1 = row[1]
scores2 = row[2]
scores3 = row[3]
# 计算每个科目在班级中的排名
subject_ranks = []
for subject, col in subject_columns.items():
subject_scores = [r[col-1] for r in worksheet.iter_rows(min_row=2, max_col=col, max_row=worksheet.max_row, values_only=True)]
rank = sum([1 for score in subject_scores if score > scores[col - 2]]) + 1
subject_ranks.append((subject, rank))
# 在Word文档模板中搜索和替换指定的标记
for paragraph in template_document.paragraphs:
if '{student_name}' in paragraph.text:
paragraph.text = paragraph.text.replace('{student_name}', student_name)
if '{student_yuwen}' in paragraph.text:
paragraph.text = paragraph.text.replace('{student_yuwen}', str(scores1))
if '{student_shuxue}' in paragraph.text:
paragraph.text = paragraph.text.replace('{student_shuxue}', str(scores2))
if '{student_yingyu}' in paragraph.text:
paragraph.text = paragraph.text.replace('{student_yingyu}', str(scores3))
if '{subject_ranks}' in paragraph.text:
ranks_text = ''
for subject, rank in subject_ranks:
ranks_text += f'{subject}排名:第{rank}名\n'
paragraph.text = paragraph.text.replace('{subject_ranks}', ranks_text)
if '{overall_rank}' in paragraph.text:
overall_scores = [sum(rs) for rs in worksheet.iter_rows(min_row=2, max_row=worksheet.max_row, min_col=2, max_col=4, values_only=True)]
overall_rank = sum([1 for score in overall_scores if score > sum(scores)]) + 1
paragraph.text = paragraph.text.replace('{overall_rank}', str(overall_rank))
if '{performance}' in paragraph.text:
if overall_rank <= 3:
performance_text = '成绩优秀'
elif overall_rank > len(overall_scores) - 3:
performance_text = '成绩差'
else:
performance_text = '成绩一般'
paragraph.text = paragraph.text.replace('{performance}', performance_text)
# 插入当前同学的评价段落到Word文档中
template_document.add_page_break()
# 保存生成的Word文档
template_document.save('output.docx')
我有一个Word模板,里面大概就一两页的内容,我想要的结果是每个学生都有自己的学习成绩说明,并且结果都在同一个文档,只是各个学生之间要分页,但是结果运行出来,只有第一个学生有结果,后面运行出来的是空白页,请问各位帮忙看看该如何解决?
您对模板的操作是不是得用上遍历循环呢?不循环,就只有一个学生哦,第一个学生。每个学生的写入得用追加模式,要不也只有一个学生,就是最后一个。
本文的内容一共分为文件打开,数据合并,数据保存三部分