# -*- coding: utf-8 -*-
""
"
XLS多选题转
Word
工具(支持A-E选项,兼容空选项)
输入格式要求:
第1列:题目
第2-6列:A-E选项(允许E为空)
第7列:答案(如:ABD 或 A,
C
,E)
输出格式:
题目内容
A. 选项A
B. 选项B
...
E. 选项E(若无则省略)
答案:A,B,D
""
"
import
os
from xlrd
import
open_workbook
from docx
import
Document
from docx.shared
import
Pt, RGBColor
from docx.enum
.text
import
WD_PARAGRAPH_ALIGNMENT
def safe_convert(cell_value):
""
"安全转换单元格内容为字符串"
""
if
cell_value is
None
:
return
""
if
isinstance(cell_value, (float,
int
)):
# 处理整数和小数
return
str
(
int
(cell_value))
if
cell_value.is_integer()
else
str
(cell_value)
return
str
(cell_value).strip()
def format_answer(ans):
""
"标准化答案格式(ABD → A,B,D)"
""
ans = ans.replace(
','
,
''
).replace(
','
,
''
).upper()
return
','
.join(sorted(set(ans))) # 去重排序
def xls_to_word(input_path, output_path):
try:
wb = open_workbook(input_path)
sheet = wb.sheet_by_index(0)
doc = Document()
doc.styles[
'Normal'
].font.
name
=
'宋体'
doc.styles[
'Normal'
].font.
size
= Pt(12)
for
row_idx
in
range(1, sheet.nrows):
row = sheet.row(row_idx)
# 处理题目和选项
question = safe_convert(row[0].value)
or
"【题目缺失】"
options = [
safe_convert(row[i].value)
for
i
in
range(1, 6) # A-E选项
]
raw_answer = safe_convert(row[6].value)
if
len(row) > 6
else
""
answer = format_answer(raw_answer)
if
raw_answer
else
"【答案缺失】"
# 添加题目(自动编号)
p_question = doc.add_paragraph()
p_question.add_run(f
"{row_idx}. {question}"
).bold = True
# 添加选项(跳过空选项)
option_labels = [
'A'
,
'B'
,
'C'
,
'D'
,
'E'
]
for
label
, content
in
zip(option_labels, options):
if
content: # 只输出非空选项
doc.add_paragraph(f
"{label}. {content}"
)
# 添加答案(蓝色+右对齐)
p_answer = doc.add_paragraph()
p_answer.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
answer_run = p_answer.add_run(f
"答案:{answer}"
)
answer_run.font.color.rgb = RGBColor(0, 0, 255) # 蓝色
doc.add_paragraph() # 题目间距
doc.save(output_path)
print(f
"转换成功:{os.path.basename(input_path)} → {os.path.basename(output_path)}"
)
return True
except Exception as e:
print(f
"转换失败:{input_path}\n错误类型:{type(e).__name__}\n错误详情:{str(e)}"
)
return False
if
__name__ ==
"__main__"
:
print(
"="
*50)
print(
"XLS多选题转Word工具"
.center(40))
print(
"="
*50)
input_file = input(
"拖入.xls文件或输入路径:"
).strip(
'"'
)
if
not
input_file.lower().endswith(
'.xls'
):
print(
"错误:仅支持.xls格式文件"
)
else
:
output_file = os.path.splitext(input_file)[0] +
"_转换结果.docx"
xls_to_word(input_file, output_file)
input(
"\n按回车键退出..."
)