python xlsxwriter 给excel单元格中部分文本文本添加颜色

1. 示意图

python xlsxwriter 给excel单元格中部分文本文本添加颜色_第1张图片

2.代码

import re
from datetime import datetime
import xlsxwriter
from xlsxwriter.workbook import Workbook


# 创建Excel对象
workbook = Workbook(filename='phone.xlsx')
worksheet = workbook.add_worksheet()

# 定义颜色
red_color = workbook.add_format({'color': 'red', 'bold': True})


# 表内容
expenses = (
    ['小米手机', '2017-01-13', 1000],
    ['苹果手机', '2017-01-14', 100],
    ['华为手机', '2017-01-16', 300],
    ['三星手机', '2017-01-20', 50],
)


row = 1
col = 0


def split_list_by_rich_word(word_list, rich_word):
    """根据rich_word将文本列表进一步拆分"""
    rt = []
    for word in word_list:
        if rich_word in word:
            tmp = word.split(rich_word)
            rt_tmp = []
            flag = False
            for t in tmp:
                if not flag:
                    flag = True
                    rt_tmp.append(t)
                else:
                    rt_tmp.append(rich_word)
                    rt_tmp.append(t)

            rt += rt_tmp
        else:
            rt.append(word)

    print('word_list:', word_list)
    return rt


def str_2_rich_string_content(s, rich_word_list, color_type):
    """构建字体颜色"""
    wl = [s]
    # 是否包含rich_word_list
    flag = False
    for r_w in rich_word_list:
        if r_w in s:
            flag = True
            wl = split_list_by_rich_word(wl, r_w)
    if not flag:
        return False, []
    # 添加颜色
    for i in range(len(wl) - 1, -1, -1):
        if wl[i] in rich_word_list:
            wl.insert(i, color_type)
    if '' in wl:
        wl.remove('')
    return True, wl

# 测试添加颜色函数
print(str_2_rich_string_content('小米雷军',['米','军'],red_color))

# 表头
worksheet.write('A1', 'Item')
worksheet.write('B1', 'Date')
worksheet.write('C1', 'Cost')
for item, date_str, cost in (expenses):
    # Convert the date string into a datetime object.
    date = datetime.strptime(date_str, "%Y-%m-%d")
    # 需要标记颜色的字符串列表
    red_word = ['小米']
    item_flag, item_rich_string = str_2_rich_string_content(s=item, rich_word_list=red_word, color_type=red_color)
    # 如果包含需要标记颜色的字段, 就以富文本的形式写入
    if item_flag:
        worksheet.write_rich_string(row, col, *item_rich_string)
    else:
        worksheet.write_string(row, col, item)
    worksheet.write_datetime(row, col + 1, date)
    worksheet.write_number(row, col + 2, cost)
    row += 1
workbook.close()

你可能感兴趣的:(python)