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

如何使用Python读取Excel文件中覆盖在单元格上的按钮?

解决Excel按钮控件读取问题

Excel中的按钮属于表单控件/ActiveX控件,是覆盖在单元格上的独立对象,并非单元格本身的数值,所以pandas或普通openpyxl读取单元格值的方式会返回NaN。要获取按钮的内容和对应位置,需要直接操作Excel的控件对象,以下是具体实现方案:

步骤说明(基于openpyxl)

  • 加载Excel文件时需关闭只读模式,才能访问控件对象
  • 遍历工作表的shapes集合,筛选出按钮控件
  • 获取按钮的对应单元格位置和按钮上的文本
  • 将按钮文本映射到pandas DataFrame的对应位置

完整代码示例

import pandas as pd
from openpyxl import load_workbook
from openpyxl.worksheet.formula import FORM_CONTROL

# 1. 先用pandas读取原始数据
df = pd.read_excel('test_sheet.xlsx', sheet_name='Table 2', skiprows=86, usecols='B:AM')

# 2. 用openpyxl加载工作簿,读取按钮控件信息
wb = load_workbook('test_sheet.xlsx', read_only=False)
ws = wb['Table 2']

# 3. 遍历所有shape,筛选按钮控件
for shape in ws.shapes:
    # 判断是否为表单控件按钮
    if shape.shape_type == 'FORM_CONTROL' and shape.form_control_type == FORM_CONTROL.BUTTON:
        # 获取按钮左上角对应的单元格
        cell = shape.top_left_cell
        # 计算该单元格在DataFrame中的行索引(skiprows=86,原始行号87对应df的第0行)
        df_row = cell.row - 87
        # 计算列索引:B列对应df的第0列,以此类推
        df_col = cell.col_idx - 2
        # 检查行和列是否在df的范围内
        if 0 <= df_row < len(df) and 0 <= df_col < len(df.columns):
            # 将按钮文本写入df对应位置
            df.iloc[df_row, df_col] = shape.text

# 4. 查看处理后的结果
print(df[:2])

注意事项

  • 如果是ActiveX控件的按钮,判断逻辑需调整:shape.shape_type == 'CONTROLS',通过shape.control.Caption获取按钮文本
  • 行索引计算需根据skiprows参数调整,确保原始Excel行号和DataFrame行号对应正确
  • 若按钮覆盖多个单元格,可根据需求选择对应单元格位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 09:12:50