python自动化办公小案例-将excel试卷转为word
作者:YXN-python 阅读量:80 发布日期:2024-05-22
安装库:
pip install python-docx
xlsx文件中字段:['题目', '选项A', '选项B', '选项C', '选项D', '答案']
更多操作参考:python办公自动化操作word—python-docx库
from docx import Document
import pandas as pd
from docx.shared import RGBColor
def read_excel(file_path=None):
df = pd.read_excel(file_path)
return df
def write_word(df, file_path):
document = Document()
for item in range(len(df)):
# 添加题目
p = document.add_paragraph('第{}题:'.format(item + 1) + df.iloc[item][0])
# 答案设为红色
p.add_run('答案:' + df.iloc[item][5]).font.color.rgb = RGBColor(0xFF, 0x00, 0x00)
if item < 394: # 区分选择题和判断题
col_count = 4 # 定义选项
# 定义选项序号
index_ = ['A、', 'B、', 'C、', 'D、', 'E、', 'F、']
for j in range(col_count): # 遍历选项
try:
if item < 50: # 适配项 区分选项是否自带选项字母
document.add_paragraph(df.iloc[item][j + 1])
continue
document.add_paragraph(index_[j] + df.iloc[item][j + 1])
except:
pass
# 保存文档
document.save(file_path)
if __name__ == '__main__':
excel_file = 'C:\\Users\\yxn\\Desktop\\a.xlsx'
word_file = 'C:\\Users\\yxn\\Desktop\\a.docx'
write_word(read_excel(excel_file), word_file)
YXN-python
2024-05-22