python给excel单元格中的某些词汇或字符设置指定颜色
程序员文章站
2022-07-13 15:29:51
...
import xlsxwriter
import pandas as pd
import re
def deal_cell_words(row, column, phrase, red, pattern, worksheet1):
red_keywords = re.findall(pattern, phrase)
print(red_keywords)
if red_keywords:
text = phrase.replace('<em>', '**').replace('</em>', '**')
li = [i for i in text.split('**') if i != '']
new_li = [row, column]
for j in range(len(li)):
if li[j] in red_keywords:
new_li.append(red)
new_li.append(li[j])
# print('new_li===>', new_li)
worksheet1.write_rich_string(*new_li)
else:
# print('phrase===>', phrase)
worksheet1.write(row, column, phrase)
def write2excel():
headings = ['id', 'title', 'from', '1小时前', 'abstract', 'url', 'keyword'] # excel表字段
workbook = xlsxwriter.Workbook('C:\\Users\\wy\\Desktop\\test1.xlsx')
worksheet1 = workbook.add_worksheet()
worksheet1.write_row('A1', headings)
red = workbook.add_format({'color': 'red'})
pattern = '.*<em.*>(.*)</em>.*'
df = pd.read_excel('C:\\Users\\wy\\Desktop\\baidu(2).xls')
datas = []
for i in df.index.values:
row_data = df.ix[i, ['id', 'title', 'from', '1小时前', 'abstract', 'url', 'keyword']].to_dict()
datas.append(row_data)
j = 1
for data in datas:
id = data['id']
title = data['title']
from1 = data['from']
time_ago = data['1小时前']
abstract = data['abstract']
url = data['url']
keyword = data['keyword']
worksheet1.write(j, 0, id)
deal_cell_words(j, 1, title, red, pattern, worksheet1)
worksheet1.write(j, 2, from1)
worksheet1.write(j, 3, time_ago)
deal_cell_words(j, 4, abstract, red, pattern, worksheet1)
worksheet1.write(j, 5, url)
worksheet1.write(j, 6, keyword)
j += 1
# exit()
workbook.close()
write2excel()
上一篇: LG工具类Util的使用(一)