日常随笔——如何把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)
相关推荐
a1117765 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得06 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
摘星编程8 小时前
OpenHarmony + RN:Calendar日期选择功能
python
Yvonne爱编码8 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
一方_self8 小时前
了解和使用python的click命令行cli工具
开发语言·python
小芳矶8 小时前
Dify本地docker部署踩坑记录
python·docker·容器
2301_822366359 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
小郎君。9 小时前
【无标题】
python
喵手9 小时前
Python爬虫实战:数据治理实战 - 基于规则与模糊匹配的店铺/公司名实体消歧(附CSV导出 + SQLite持久化存储)!
爬虫·python·数据治理·爬虫实战·零基础python爬虫教学·规则与模糊匹配·店铺公司名实体消岐
喵手9 小时前
Python爬虫实战:国际电影节入围名单采集与智能分析系统:从数据抓取到获奖预测(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集国际电影节入围名单·从数据抓取到获奖预测