excel 中 python 的动态值字符串的富文本

Rich text for the dynamic value string in excel for python

我已经使用了 python 的 xlsxwriter 和 openpyxl 模块来获取丰富的字符串,但是它们没有提供足够的灵活性来搜索动态字符串的特定单词并突出显示该单词。 有人对此有更好的选择吗?或者,我试图将动态字符串拆分为并尝试在两者之间添加样式以与 xlsxwriter.write_rich_string() 格式合并。 下面是示例代码: ....这里有一些起始代码

completestring="Whosebug is best site" #this will be a dynamic string ,and need to highlight **best** here

str1="Whosebug is"
str2="best"
str3="site"
bold= workbook.add_format()
bold.set_bold()
bold.set_font_color('red')

stringpart=[str1,bold,str2,str3]

worksheet.write_rich_string('A1',*stringpart)

I have used xlsxwriter and openpyxl module of python for rich string but they don't provide that much flexibility for searching specific word of dynamic string and highlight that one.

这是可以在Python中处理的事情。你只需要想出一种方法来根据一个词拆分字符串并在列表中维护这个词。

这是一种方法:

import re
import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True, 'color': 'red'})

# Make the column wider for clarity.
worksheet.set_column('A:A', 30)

# Some sample test data.
strings = ["The best website",
           "The bestest website",
           "The best of the best",
           "best of the best",
           "    best of the best    ",
           "The BEST website"]

# Iterate over the strings.
for row_num, string in enumerate(strings):
    # Split the sentence on the word "best", on word boundaries.
    segments = re.split(r'(\bbest\b)', string)

    if len(segments) == 1:
        # String doesn't have a match, write as a normal string.
        worksheet.write(row_num, 0, string)
    else:
        # Iternate through the segments and add a format before the matches.
        tmp_array = []
        for segment in segments:
            if segment == 'best':
                # Add a bold format before the matched word.
                tmp_array.append(bold)
                tmp_array.append(segment)
            elif not segment:
                # Ignore blank segments.
                pass
            else:
                tmp_array.append(segment)

        worksheet.write_rich_string(row_num, 0, *tmp_array)
workbook.close()

输出: