日常随笔——如何把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)
相关推荐
Scott9999HH6 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
EIP低代码平台6 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
AI云海7 小时前
python 列表、元组、集合和字典
开发语言·python
Am-Chestnuts7 小时前
Kimi长回答批量导出Word:DS随心转实践
word
二十雨辰7 小时前
[爬虫]-Urllib
爬虫·python
玉鸯9 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_4462608510 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao10 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
qetfw10 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具