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

相关推荐
xiaopai9452 小时前
工程项目管理系统选型:WPS/Excel为何难以替代专业系统的数据关联逻辑
excel·wps·项目管理系统·建米软件
灵析表格4 小时前
Excel连接MySQL的函数化革命:灵析表格MySQL函数族业务应用分析
数据库·mysql·adb·excel·wps·灵析表格·excel公式盒子
许彰午16 小时前
在PowerBuilder里手写Excel导出——OLE控制Excel的完整方案
excel
admin0051 天前
进销存软件与Excel的边界:什么时候该从Excel升级到专业软件
excel·企业管理·财务管理·进销存管理
灵析表格1 天前
json_ObjectToKV 函数深度研究报告
json·excel·wps·灵析表格·excel公式盒子
观远数据1 天前
Excel、自研、还是换BI?产品VP拆解三条数据分析路线的隐性成本
大数据·数据分析·excel
娇气的妮巴1 天前
老Excel数据怎么迁到ERP系统
java·前端·excel
2601_965912831 天前
PDF转Excel工具横向评测:6款免费方案实测数据对比
pdf·excel·notepad++
一行注释2 天前
纯前端通过xlsx.js导出Excel表格:完整示例与实战指南
前端·javascript·excel
QuartusII72 天前
Excel中alt+enter单元格内无法换行
excel