1. 示意图
2.代码
import re
from datetime import datetime
import xlsxwriter
from xlsxwriter.workbook import Workbook
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]
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):
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()