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

相关推荐
哆啦A梦158811 小时前
商城后台管理系统 03 Vue项目-实现表格导出EXCEL表格
前端·vue.js·excel
xingzhemengyou111 小时前
python pandas操作excel
python·excel·pandas
小小心LOVE12 小时前
Vue3 安装和使用 vue-office来实现 Word、Excel 和 PDF 文件的预览
vue.js·word·excel
cyhysr12 小时前
oracle的model子句让sql像excel一样灵活2
sql·oracle·excel
oh,huoyuyan1 天前
【界面案例】火语言RPA读取Excel文件,循环写入界面表格
excel·rpa
2501_907136821 天前
Excel数据根据标题行自动匹配合并到指定模板文件
excel·软件需求
分***81 天前
批量识别身份证并导出excel工具分享,身份证识别工具离线识别 + 字段精准优化,Win10/11 直接用
excel·身份证识别
runepic1 天前
Python 批量合并多个 Excel 数据(自动补 0 + 生成明细)
java·python·excel
hellotutu1 天前
Java 读取 Excel 文件
java·开发语言·excel
yivifu1 天前
Excel中Lookup函数实现临界点归入下一个等级的方法
java·前端·excel