日常随笔——如何把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)
相关推荐
Cenxi25 分钟前
f-string 完全手册:60 题从入门到实战
python
2601_9622998829 分钟前
Python编写Linux命令指南
linux·python·开发·命令·指南
Z59981784131 分钟前
c#软件开发学习笔记--WPF(MVVM框架)
笔记·学习·c#
此冬歌咏32 分钟前
自动化服务器运维监控系统(python+shell)
linux·运维·服务器·开发语言·python·自动化
zhanghaha131434 分钟前
Python进阶教程:23_Scrapy 爬虫框架 零基础超详细教程
python·信息可视化
爱读源码的大都督1 小时前
DeepSeek面试官问:生产RAG系统回答不准确,该如何定位和优化?这样回答,能让面试官当场给你Offer!
java·后端·python
“AI国潮设计-小江”1 小时前
【Python实战】SDXL精准控制“普宁英歌舞×星空蛋糕”IP落地,附核心Prompt与商用授权思路
开发语言·人工智能·python·prompt·aigc
k4m7v2pz1 小时前
从 Python 搬到 Rust:pyglet MIDI DAW 变成 egui 鬼畜采样器的迁移复盘
开发语言·python·rust
tryCbest1 小时前
FastAPI中passlib包的作用
python·fastapi·passlib
心中有你02142 小时前
Python Tkinter 情侣恋爱日记桌面小程序(本地文件存储,无数据库)
开发语言·python