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

相关推荐
dgiij7 小时前
excel大表导入数据库
数据库·mysql·node.js·excel
多敲代码防脱发8 小时前
导出导入Excel文件(详解-基于EasyExcel)
java·开发语言·jvm·数据库·mysql·excel
琉璃℡初雪10 小时前
vue2/3 中使用 @vue-office/docx 在网页中预览(docx、excel、pdf)文件
vue.js·pdf·excel
河山入梦来1 天前
Excel表的导入与导出
excel
wtsolutions2 天前
Excel-to-JSON插件专业版功能详解:让Excel数据转换更灵活
json·excel·excel-to-json·wtsolutions·专业版
梦幻通灵2 天前
Excel分组计算求和的两种实现方案
前端·excel
莫负初2 天前
Excel使用VBA批量计算指定列的中位数和标准差并筛选指定列数据
数据分析·自动化·excel·vba·方差·标准差
杜子腾dd2 天前
17.Excel:实用的 VBA 自动化程序
数据分析·自动化·excel
是孑然呀2 天前
【小记】excel vlookup一对多匹配
excel
chaodaibing2 天前
pandas读取pymysql和解析excel的一系列问题(版本不匹配)
excel·pandas