python在Word文件指定的文字下划线
效果展示
原始文件
划线后文件
代码实现
# coding:utf-8
import os
from win32com.client import Dispatch
def get_string_index(substring, string):
"""
获取同一字符串中的多个相同字符串的起始索引
:param substring: 需查找的字符串
:param string: 被查找的字符串
:return:
"""
indices = []
index = string.find(substring)
while index != -1:
indices.append(index)
index = string.find(substring, index + 1)
return indices
def word_underline_text(input_path, substring, out_path=None):
"""
给Word文档中的指定字符下划线
:param input_path: word文件路径
:param substring: 需划线的字符
:param out_path: 输出文件路径
:return:
"""
if not out_path:
out_path = f'{os.path.splitext(input_path)[0]}_注释{os.path.splitext(input_path)[1]}'
# app = Dispatch('kwps.Application') # wps use
app = Dispatch('Word.Application')
app.Visible = 0
doc = app.Documents.Open(input_path)
for paragraph in doc.paragraphs:
index_list = get_string_index(substring, paragraph.Range.Text)
for idx in index_list:
for x in range(len(substring)):
paragraph.Range.Characters(idx + x + 1).Font.Underline = 6 # 设置下划线
paragraph.Range.Font.UnderlineColor = 255 # 设置下划线颜色为红色
doc.SaveAs(out_path)
app.Quit()
f_p = r"C:\Users\abc\Desktop\合同.docx"
word_underline_text(f_p, '测试文档')
本文来自博客园,仅供参考学习,如有不当之处还望不吝赐教,不胜感激!转载请注明原文链接:https://www.cnblogs.com/rong-z/p/17877161.html
作者:cnblogs用户