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

相关推荐
hhzz2 小时前
EasyPoi的核心映射工具:@Excel注解详解
java·服务器·excel·springboot·easypoi
小妖6664 小时前
excel 本地sheet往服务器上粘贴时,表格宽度没有粘过来
excel
yongui478348 小时前
使用C#实现Excel实时读取并导入SQL数据库
数据库·c#·excel
hanjq_code10 小时前
java使用阿里的easyExcel解决把excel每行的数据转成excel表格格式数据并打包成ZIP下载
java·开发语言·excel
牛猫Data10 小时前
Power BI为什么不能完全取代Excel?
microsoft·数据分析·excel·database·数据可视化·powerbi
小当家.10510 小时前
《Java操作Excel实战教程:Apache POI从入门到精通》
java·apache·excel
vortex51 天前
【小技巧】用 VLOOKUP 实现表格合并
excel
宫瑾1 天前
Excel常用操作记录
excel
老蒋每日coding1 天前
Java解析Excel并对特定内容做解析成功与否的颜色标记
java·开发语言·excel
博风1 天前
bartender打印软件连接excel文档进行标签打印
excel