excel标记文本中的关键词加红加粗

任务:

有这么一张表,关键词为 word,文本内容为 text,现在想把 text 中的 word 标红加粗,如果数据量少,文本段手动标还可以,多起来就不太方便了

代码:

python 复制代码
import pandas as pd
import xlsxwriter

df = pd.read_excel('data.xlsx')
out_path = 'label.xlsx'
workbook = xlsxwriter.Workbook(out_path)
worksheet = workbook.add_worksheet('Sheet1')  # 创建 sheet1
bold_red = workbook.add_format({'bold': True, 'color': 'red'})  # 配置加粗,红色

header = df.columns.tolist()
worksheet.write_row(0, 0, header)  # 在 0行0列写入表头

for i, row in df.iterrows():
    word = row['word']
    text = row['text']
    for h in range(len(header)):
        if header[h] != 'text':  # 保留其他原始列的值
            worksheet.write(i + 1, h, row[header[h]])
        else:
            if word in str(text):
                word_len = len(word)
                word_index = text.find(word)
                # 关键词在开头或结尾需要特殊处理
                if text.startswith(word):
                    worksheet.write_rich_string(i + 1, h, bold_red, word, text[word_index + word_len:])
                elif text.endswith(word):
                    worksheet.write_rich_string(i + 1, h, text[:word_index], bold_red, word)
                else:
                    worksheet.write_rich_string(i + 1, h, text[:word_index], bold_red, word, text[word_index + word_len:])
            else:
                worksheet.write(i + 1, h, text)  # 不包含 word 的原文正常写入

workbook.close()

可以看到每条 text 中出现的第一个 word 标红加粗了,但后面的就不会了,如果要把第二个也加粗,那需要另寻他法

相关推荐
全干engineer4 小时前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Fireworkitte4 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
chemddd11 小时前
excel 工作需要会的
excel
醇氧13 小时前
【wps】 excel 删除重复项
excel·wps
盛夏绽放21 小时前
Vue3 中 Excel 导出的性能优化与实战指南
vue.js·excel
Tomorrow'sThinker1 天前
[特殊字符] Python 自动查找替换 Excel 单元格内容 —— 高效批量处理
excel
Shipley Leo1 天前
如何在Excel中每隔几行取一行
excel
bing_1581 天前
Excel 数据透视表不够用时,如何处理来自多个数据源的数据?
excel
想要入门的程序猿1 天前
Qt写入excel
数据库·qt·excel
爱代码的小黄人2 天前
Excel VLOOKUP函数使用详解:原理、格式、常见错误与解决方案
excel