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

相关推荐
葡萄城技术团队16 小时前
模拟运算表全解析:从 Excel 的两变量限制到 SpreadJS 的不限变量 | SpreadJS 新版本 特性解析
excel
hoiii18718 小时前
C# Txt/Excel/Access 导入导出工具
开发语言·c#·excel
小当家.10518 小时前
Excel AI Converter:用 大模型 自动转换excel表格格式
人工智能·excel·工具
2501_9307077818 小时前
使用 C# 在 Excel 中合并并居中单元格
开发语言·c#·excel
ComPDFKit19 小时前
2026 PDF 表格提取工具横评:15 款工具实测对比
pdf·excel·pdf表格提取·pdf to excel·pdf数据提取
技术小甜甜2 天前
[办公效率] Excel 表格越做越乱,先整理字段、格式还是公式?
数据库·excel·办公效率·数据整理
SunnyDays10112 天前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
itgather2 天前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
葡萄城技术团队2 天前
【SpreadJS 新版本特性揭秘】完美对齐 Excel 365:V19.1 单元格内嵌图片架构解析
excel
qq_422152572 天前
Excel 转 CSV 工具怎么选?格式兼容、编码问题与数据导出方案实测
excel