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 标红加粗了,但后面的就不会了,如果要把第二个也加粗,那需要另寻他法

相关推荐
用户0332126663678 小时前
Python 自动化办公:如何从零快速生成结构清晰的 Excel 报表
python·excel
千桐科技8 小时前
qData 数据中台专业版功能解析:告别 Excel 与 SQL 拼凑,打通系统合并的可追踪数据链路
数据库·sql·excel·qdata
百事牛科技10 小时前
从局部到整体:Excel限制功能的几种实用设置
windows·excel
ProcessOn官方账号15 小时前
ProcessOn Office 插件上线:在 Word / Excel / PPT 里直接画流程图
word·excel·插件·office·processon
reasonsummer2 天前
【办公类-53-12】20261016(预测)Python模仿制作2026学年第二学期校历(excel+pdf,上下学期都包含)
pdf·excel
泡海椒2 天前
JQuick-Excel 自定义 SPI Provider:用 fullName 扩展 TRANSFORM 函数
驱动开发·excel
泡海椒2 天前
从 XML 到 Excel:JQuick-Excel 代理与解析器如何协作
xml·excel
优选资讯2 天前
Excel 批量打印标签的完整流程
excel
雪宫街道3 天前
SpringBoot - POI实现Excel 导入与导出
spring boot·后端·excel
Data-Miner3 天前
数据分析,除了Excel数据透视表,还有什么工具?——2026 专业精选推荐榜
microsoft·数据分析·excel