目前参与的项目,最后需要对docx文件进行高亮,方法找的挺久的,就总结一下。也方便同样有这个需求的人。
用到的pip包为python-docx
安装命令为:
pip install python-docx
一、对文本进行高亮
from docx.enum.text import WD_COLOR_INDEX
from docx import Document
# 打开文档
document = Document(docx_path)
# 获取到第四个段落的第二个文本的字体信息
font = document.paragraphs[4].runs[2].font
# 将高亮颜色设为黄色
font.highlight_color = WD_COLOR_INDEX.YELLOW
# 保存高亮文本
document.save(highlight_docx_path)
上面是对第四个段落的第二个字进行高亮,如果需要对一段高亮。则需要进行遍历即可。
二、对表格单元格进行高亮
from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
# 打开文档
document = Document(docx_path)
# 设置高亮的颜色 FFFF00为黄色 这个可查RGB表获取
shading_elm = parse_xml(r'<w:shd {} w:fill="FFFF00"/>'.format(nsdecls('w')))
# 第一个表
table = document.tables[0]
# 第一个单元格
cell = table.cell(0,0)
# 设置颜色
cell._tc.get_or_add_tcPr().append(shading_elm)
# 保存高亮文件
document.save(highlight_docx_path)
上面是对一个单元格进行高亮,如果想对多个单元格进行黄色高亮,则需要重新声明一个新的shading_elm_1。否则只使用一个shading_elm,最后结果只能保存最后一个高亮的单元格。
# 重新声明一个新的高亮
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="FFFF00"/>'.format(nsdecls('w')))
# 第二个单元格
cell = table.cell(0, 1)
# 进行高亮
cell._tc.get_or_add_tcPr().append(shading_elm_1 )
对于其他单元格也是同理。