利用python操作excel输出带颜色的字体

需求:

将一些文本输出到excel,但需要将满足某种条件的字体突出显示,例如标红.

如何做:

利用xlsxwriter的write_rich_string

示例:

from xlsxwriter.workbook import Workbook

workbook = Workbook('sequences.xlsx')
worksheet = workbook.add_worksheet()

red = workbook.add_format({'color': 'red'})
green = workbook.add_format({'color': 'green'})

sequences = [
'ACAAGATG',
'CCATTGTC',
'CCCCGGCC',
'CCTGCTGC',
'GCTGCTCT',
'CGGGGCCA',
'GGCCACCG',
]

worksheet.set_column('A:A', 40)

for row_num, sequence in enumerate(sequences):

    format_pairs = []

# Get each DNA base character from the sequence.
for base in sequence.upper():

    # Prefix each base with a format.
    if base == 'A' or base == 'T':
        format_pairs.extend((red, base))

    elif base == 'G' or base == 'C':
        format_pairs.extend((green, base))

    else:
        # Non base characters are unformatted.
        format_pairs.append(base)

worksheet.write_rich_string(row_num, 0, *format_pairs)

workbook.close()

输出结果为:


利用python操作excel输出带颜色的字体_第1张图片
image.png

参考链接

Python: list of strings, change color of character if found (using xlsxwriter)

你可能感兴趣的:(利用python操作excel输出带颜色的字体)