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, '测试文档')
posted @ 2023-12-05 14:37  cnblogs用户  阅读(303)  评论(0编辑  收藏  举报