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

相关推荐
weixin_4935036717 小时前
商会系统里的在线文件预览:PDF/Word/Excel 三种实现与选型(Node + 前端实战)
pdf·word·excel
asdzx6720 小时前
Python 解析 Excel 数据、图片与图表的实现方案
python·excel
慧都小妮子20 小时前
GcExcel 服务端 Excel 组件:无需安装 Office 的 Java/.NET 报表方案
java·.net·excel·gcexcel·服务端excel组件
The Future is mine1 天前
Excel如何只允许对部分表格内容进行修改
excel
2601_962099461 天前
Python xlwt设置excel单元格字体及格式
python·excel·xlwt·样式设置·单元格格式
葡萄城技术团队2 天前
不会写 SUMIFS 也能做汇总?用 SpreadJS AI 生成并解释 Excel 公式
人工智能·excel
2501_933670792 天前
采购运营校招Excel能力清单:函数、透视表、ERP数据与SQL入门
数据库·sql·excel
netho03 天前
影刀RPA初级证书+ Excel 全自动数据看板
excel·rpa
2501_930707783 天前
使用C#代码设置 Excel 单元格的背景颜色和图案
excel
ms365copilot3 天前
Excel Copilot聊天历史|关闭文件后,还能找回之前的AI分析对话
人工智能·excel·copilot