You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python输出Excel文件中所有粗体或斜体格式的字符串

提取Excel中粗体/斜体单元格内容的实现方案

你已经掌握了单个单元格的字体格式判断方法,只需要补全全表遍历逻辑即可实现需求,openpyxl中粗体判断对应属性为cell.font.bold,斜体对应属性为cell.font.italic,完整可运行代码如下:

import openpyxl as xl

file_path = '/Users/uiswork/Downloads/members_of_uni_bodies.xlsx'
wb = xl.load_workbook(file_path)
ws = wb.active
# 切换指定工作表可使用以下写法,替换为实际表名即可
# ws = wb["工作表名称"]

format_cells = []

# 遍历工作表所有已使用单元格
for row in ws.iter_rows():
    for cell in row:
        # 跳过空值单元格
        if cell.value is None:
            continue
        cell_bold = cell.font.bold
        cell_italic = cell.font.italic
        # 匹配粗体或斜体格式的单元格
        if cell_bold or cell_italic:
            format_cells.append({
                "coord": cell.coordinate,
                "value": str(cell.value).strip(),
                "font_type": "bold" if cell_bold and not cell_italic else ("italic" if cell_italic and not cell_bold else "bold+italic")
            })

# 打印输出结果
for item in format_cells:
    print(f"单元格{item['coord']},格式:{item['font_type']},内容:{item['value']}")

注意事项

  • 你之前测试A1单元格返回False属于正常结果,说明A1本身未设置斜体格式,属性判断逻辑没有问题
  • openpyxl仅能识别单元格直接设置的字体格式,如果单元格的粗/斜体来自条件格式、主题样式继承,脚本无法直接识别,需要先在Excel中将这类动态格式转换为单元格固定格式后再运行脚本
  • 如果需要遍历整个工作簿的所有工作表,只需要在加载工作簿后增加一层工作表循环,将上述单元格遍历逻辑嵌套在内即可

内容的提问来源于stack exchange,提问作者teffies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 06:21:47