日常随笔——如何把excel题库转换为word打印格式

将Excel题库转换为Word可以通过编程的方式实现。以下是一个使用Python的示例代码,该代码使用openpyxl库读取Excel文件,并使用python-docx库创建和保存Word文档。

首先,请确保已经安装了 openpyxl 和 python-docx 库。可以使用以下命令进行安装:

python 复制代码
pip install openpyxl python-docx

然后,使用以下代码将Excel题库转换为Word文档:

python 复制代码
import openpyxl
from docx import Document
from docx.shared import Pt

def excel_to_word(excel_file, word_file):
    # 打开Excel文件
    wb = openpyxl.load_workbook(excel_file)
    
    # 获取第一个工作表
    sheet = wb.active
    count = 1
    # 创建Word文档
    doc = Document()
    first_line = True
    # 遍历Excel表格中的每一行
    for row in sheet.iter_rows(values_only=True):
		# 跳过首行
        if first_line:
            first_line = False
            continue
        # 第一列为问题,第二列为答案
        question = row[0]
        answer_mode = row[1]
        answer_choice = row[3]
        answer = row[4]

        answer_choices = answer_choice.split("|")
        if len(answer_choices) == 1:
            answer_choices = answer_choice.split("|")
        choice  = ""
        C = ["A", "B", "C", "D", "E", "F", "G"]
        
        for index, value in enumerate(answer_choices):
            choice += C[index] + ": " + str(value) + "   "
        
        # 调整间距
        # doc.paragraph_format.space_before = Pt(12)  # 段前12磅
        # doc.paragraph_format.space_after = Pt(12)   # 段后12磅
        # 将问题和答案写入Word文档
        doc.add_paragraph(f"问题{count}: {question}({answer_mode}) \n选项: {choice} \n答案: {answer}")
        # doc.add_paragraph(f"选项: {choice}")
        # doc.add_paragraph(f"答案: {answer}")
        
        # 添加分隔线
        # doc.add_paragraph("--------------------")
        count += 1
    
    # 保存Word文档
    doc.save(word_file)

# 设置Excel和Word文件的路径
excel_file = "复习资料.xlsx"
word_file = "题库.docx"

# 调用函数将Excel题库转换为Word文档
excel_to_word(excel_file, word_file)
相关推荐
32码奴3 分钟前
C#基础知识
开发语言·c#
aiweker2 小时前
Selenium 使用指南:从入门到精通
python·selenium·测试工具
SteveKenny3 小时前
Python 梯度下降法(六):Nadam Optimize
开发语言·python
dreadp5 小时前
解锁豆瓣高清海报(二) 使用 OpenCV 拼接和压缩
图像处理·python·opencv·计算机视觉·数据分析
Tester_孙大壮5 小时前
第32章 测试驱动开发(TDD)的原理、实践、关联与争议(Python 版)
驱动开发·python·tdd
小王子10249 小时前
设计模式Python版 组合模式
python·设计模式·组合模式
来恩10039 小时前
C# 类与对象详解
开发语言·c#
唐棣棣10 小时前
22.Word:小张-经费联审核结算单❗【16】
word·ms
Mason Lin10 小时前
2025年1月22日(网络编程 udp)
网络·python·udp
清弦墨客10 小时前
【蓝桥杯】43697.机器人塔
python·蓝桥杯·程序算法