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

相关推荐
Channing Lewis5 小时前
sharepoint 共享excel,如何实现某个 sheet 别人只读,但是另一个 sheet 可以编辑
excel·sharepoint
霸王蟹1 天前
前端项目Excel数据导出同时出现中英文表头错乱情况解决方案。
笔记·学习·typescript·excel·vue3·react·vite
开开心心就好1 天前
高效账号信息管理工具,可安全随机生成密码
javascript·安全·docker·智能手机·pdf·word·excel
勇太的数分之旅1 天前
Excel大厂自动化报表实战(互联网金融-数据分析周报制作上)
金融·数据分析·自动化·excel·数据可视化
勇太的数分之旅1 天前
Excel大厂自动化报表实战(互联网金融-数据分析周报制作中)
金融·数据分析·自动化·excel·数据可视化
一晌小贪欢1 天前
【Python办公】使用pandas批量读取csv保存为Excel
python·excel·pandas·读取excel·python办公·excel转csv
小志开发1 天前
Excel VBA入门指南:解锁开发工具与编写你的第一个程序
microsoft·数据分析·excel
_oP_i1 天前
优化 Excel 文件可以提升文件性能、减少文件大小并加快计算速度
excel
Charlotte_jc1 天前
完美解决openpyxl保存Excel丢失图像/形状资源的技术方案
开发语言·python·excel·openpyxl
板栗栗-71 天前
Excel词典(xllex.dll)文件丢失或损坏导致功能异常?别慌!专业修复策略来了!
excel·dll·dll修复·dll错误·dll缺失