python的docx库实现了自动化需要的大部分常用的功能
但是有很多细节的功能没有实现 而且该库已经停止更新
有很多效果无法实现 如果有需要实现特定效果, 但是又找不到方法的 可以联系我
email: 491870929@qq.com
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def doc_table_highlight_txt(cell, color):
"""
高亮单元格中的文字
Args:
cell:
color:
Returns:
"""
shade_obj = OxmlElement('w:shd')
shade_obj.set(qn('w:fill'), color)
if cell._element.xpath('.//w:rPr'):
cell._element.xpath('.//w:rPr')[0].append(shade_obj)
else:
a = cell.text
cell._element.clear_content()
p = cell.add_paragraph()
r = p.add_run(a)
rpr_obj = OxmlElement('w:rPr')
rpr_obj.append(shade_obj)
r._element.append(rpr_obj)
测试用的小demo
# 写一个小demo
# 创建文档
document = Document()
# 创建3*3表格
table = document.add_table(rows=3, cols=3, style='Table Grid')
# 填充数据
for i in range(3):
for j in range(3):
cell = table.cell(i, j)
p = cell.add_paragraph()
r = p.add_run('hello world')
r.text = f"Row {i+1}, Column {j+1}"
# 设置第二行第二列的单元格背景颜色为黄色(RGB 值为 (255, 255, 0))
if i == 1 and j == 1:
doc_table_highlight_txt(cell, 'FFFF00')
document.save('demo.docx')