import?xlrd
import?random
from?docx?import?Document
from?docx.shared?import?Pt,?RGBColor
from?docx.enum.text?import?WD_ALIGN_PARAGRAPH
#?讀取excel
data?=?xlrd.open_workbook('data3.xlsx')
sheet?=?data.sheet_by_index(0)??#?獲取工作表
class?Question:
????pass
def?createQuestion():
????questionlist?=?[]
????for?i?in?range(sheet.nrows):
????????if?i?>?1:
????????????obj?=?Question()
????????????obj.subject?=?sheet.cell(i,?1).value??#?題目
????????????obj.questiontype?=?sheet.cell(i,?2).value??#?題型
????????????obj.option?=?[]
????????????obj.option.append(sheet.cell(i,?3).value)??#?a
????????????obj.option.append(sheet.cell(i,?4).value)??#?b
????????????obj.option.append(sheet.cell(i,?5).value)??#?c
????????????obj.option.append(sheet.cell(i,?6).value)??#?d
????????????obj.score?=?sheet.cell(i,?7).value??#?分值
????????????questionlist.append(obj)??#?obj添加到questionlist列表里
????random.shuffle(questionlist)??#?將序列所有的元素隨機(jī)排序
????return?questionlist
#?生成word試卷
def?createPaper(filename,?papername,?questionlist):
????document?=?Document()
????#?頁眉頁腳的信息
????section?=?document.sections[0]
????header?=?section.header
????p1?=?header.paragraphs[0]
????p1.text?=?papername
????footer?=?section.footer
????p2?=?footer.paragraphs[0]
????p2.text?=?"內(nèi)部試題,禁止泄露."
????#?試卷基本信息
????title?=?document.add_heading(papername,?level=1)
????title.alignment?=?WD_ALIGN_PARAGRAPH.CENTER??#?居中對(duì)齊
????p3?=?document.add_paragraph()
????p3.add_run('姓名:______')
????p3.add_run('所屬部門:______')
????p3.alignment?=?WD_ALIGN_PARAGRAPH.CENTER??#?對(duì)齊居中
????#?試題信息
????for?question?in?questionlist:
????????subject?=?document.add_paragraph()
????????run?=?subject.add_run(question.subject)
????????run.bold?=?True??#?題目字體加粗
????????subject.add_run('【%s】分'?%?str(question.score))
????????random.shuffle(question.option)??#?打亂選項(xiàng)的順序
????????for?index,?option?in?enumerate(question.option):
????????????document.add_patagraph(('ABCD')[index]?+?str(option))
????document.save(filename)
for?i?in?range(10):??#?生成10份試卷
????questionlist?=?createQuestion()
????createPaper('paper'?+?str(i+1)?+?'.docx',?'2021年第一季度內(nèi)部考試',?questionlist)
2021-03-16
print("重新安裝了一下python-docx模塊問題解決了?")