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

相关推荐
SunnyDays10117 小时前
Python操作Excel批注:从基础添加到高级自定义的完整指南
开发语言·python·excel
Eiceblue9 小时前
Python 操作 Excel:数据分组、分类汇总与取消分组全解
开发语言·python·excel
城数派10 小时前
2026年500米分辨率DEM地形数据(全球/全国/分省/分市)
数据库·arcgis·信息可视化·数据分析·excel
SunnyDays101111 小时前
Python 操作 Excel 超链接:添加网页、文件、工作表和图片链接
python·excel
专注VB编程开发20年13 小时前
我制作excel工作簿的选项卡,发给deep seek, 昨天修改了一天
前端·vue.js·excel
星越华夏1 天前
python办公自动化,csv文件/excel文件差集合并
开发语言·python·excel
开开心心就好1 天前
180套模板的图片艺术拼接实用工具
linux·服务器·网络·spring·智能手机·maven·excel
仰望.2 天前
vxe-table 导出 Excel 进阶教程:自定义样式与高级功能
前端·javascript·vue.js·excel·vxe-table·vxe-ui
Access开发易登软件2 天前
Access 和 SQLite,根本不在一个赛道上
java·jvm·数据库·sqlite·excel·vba·access开发
biuyyyxxx3 天前
Excel常见异常
excel