Rich text for the dynamic value string in excel for python

冷暖自知 提交于 2020-02-25 06:20:50

问题


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. Does anyone have better option for this? alternatively, I am trying to split the dynamic string into and trying to add styles in between to incorporate with the xlsxwriter.write_rich_string() format. below is the sample code: ....some starting code here

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

str1="Stackoverflow 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)

回答1:


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.

This is something that can be handled in Python. You just need to figure out a way to split stings based on a word and maintain the word in the list.

Here is one way to do it:

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()

Output:



来源:https://stackoverflow.com/questions/59297263/rich-text-for-the-dynamic-value-string-in-excel-for-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!