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

相关推荐
未来之窗软件服务20 小时前
Excel物业台帐租金合同资产—万象EXCEL应用(28) —东方仙盟
excel·仙盟创梦ide·东方仙盟·万象excel
AI刀刀1 天前
豆包智能体 7 月 15 日全面下线:技术解读、数据迁移与自动化备份方案
运维·人工智能·自动化·word·excel·ai导出鸭
xurime1 天前
Excelize 开源十周年,发布 2.11.0 版本
golang·开源·github·excel·导出·导入·excelize·基础库
littleBoy7772 天前
Excel 文件合并工具
excel
wtsolutions2 天前
Excel-to-JSON本地化Excel插件发布 - 在Excel中安全离线转换数据
安全·json·excel
用户298698530142 天前
Python 实现 Excel 与 TXT 文本的高效转换与导出
后端·python·excel
程序员小郭832 天前
Java + POI 实现高性能Excel导出(支持普通List、MyBatis Cursor流式导出、VO适配)
spring boot·后端·excel
AI导出鸭PC端4 天前
告别导出难题:AI 导出鸭助力 Claude 输出 excel 一站式实现
人工智能·ai·excel·豆包·ai导出鸭
Am-Chestnuts4 天前
DeepSeek 表格如何导出 Word/Excel:Markdown 表格、CSV 与 DS随心转方案对比
word·excel
城数派4 天前
2000-2026年我国省市县三级逐月NDVI数据(Shp/Excel格式)
excel