向word中写入带颜色的文字
#!/usr/bin/env python# encoding: utf-8'''@author: JHC@license: None@contact: JHC000abc@gmail.com@file: 生成高亮答案提示文件.py@time: 2022/4/24 15:02@desc:'''import pymysqlfrom docx import Documentfrom docx.shar
·
#!/usr/bin/env python
# encoding: utf-8
'''
@author: JHC
@license: None
@contact: JHC000abc@gmail.com
@file: 生成高亮答案提示文件.py
@time: 2022/4/24 15:02
@desc:
'''
import pymysql
from docx import Document
from docx.shared import RGBColor
host = 'localhost'
port = 3306
user = 'root'
password = '123456'
db = 'questionsbank'
document = Document()
mysql = pymysql.connect(host=host, user=user, password=password, port=port, db=db)
# 2.新建个查询页面
cursor = mysql.cursor()
# 3编写sql
sql = "select title from maogai"
sql2 = "select key1,key2,key3,key4,key5 from maogai"
sql3 = "select answer from maogai"
sql4 = "select type from maogai"
# sql5 = "select id from xingce"
# 4.执行sql
cursor.execute(sql)
results_title = cursor.fetchall()
cursor.execute(sql2)
results_key = cursor.fetchall()
cursor.execute(sql3)
results_answer = cursor.fetchall()
cursor.execute(sql4)
results_type = cursor.fetchall()
# cursor.execute(sql5)
# results_id = cursor.fetchall() # 用于返回多条数据
for i in range(len(results_title)):
p = document.add_paragraph(str(i+1)+". "+"["+results_type[i][0]+"] ")
answer = p.add_run("["+results_answer[i][0]+"]")
# 字体颜色
answer.font.color.rgb = RGBColor(250, 0, 0)
p.add_run(results_title[i][0] + "\n")
try:
if results_type[i] != (None, None, None, None, None):
# p.add_run("\n\t\t".join(results_key[i]))
for j in results_key[i]:
print(results_answer[i], j.split(".")[0])
if j.split(".")[0] in list(results_answer[i][0]):
key = p.add_run("\t"+j+"\n")
key.font.color.rgb = RGBColor(0, 255, 0)
else:
p.add_run("\t" + j + "\n")
else:
p.add_run("\n")
except Exception as e:
print(e)
document.save('./test.docx')
更多推荐
已为社区贡献7条内容
所有评论(0)