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

如何调整Ruby代码读取横向Excel列并验证应用界面字段

调整Ruby代码以支持横向结构Excel表格的界面验证

现有Ruby代码可处理纵向结构的Excel表格,完成单元格记录与应用界面字段的匹配验证,但无法读取横向结构表格的记录(例如表格第3行从Leitura列开始的[Invisivel, Invisivel,Habilitado,Invisivel]这类横向排布的状态值)并完成界面验证,需对代码进行如下调整:

原代码

Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open('c:/temp/gab.xls', "r")
sheet = book.worksheet 4
xls_offset = 1
row_offset = 2
sheet.each_with_index(xls_offset) do |row, idx|
  expected_tooltip = row[1]
  break if row[1].nil?
  expect(page).to have_css("tr.tvRow:nth-child(#{row_offset+idx}) .tvCell:nth-child(6) img[tooltip='#{expected_tooltip}']")
end

可处理的纵向结构表格

字段(fields)状态(status)
LeituraInvisível
HidrometroInvisível
DiametroInvisível
LacreObrigatório

待处理的横向结构表格

编码(code)状态(situation)标签(tab)读取(leitura)水表(hidrometro)管径(diametro)封条(lacre)
8okBInvisivelInvisivelHabilitadoInvisivel
9okCInvisivelInvisivelHabilitadoInvisivel
10okCInvisivelInvisivelHabilitadoInvisivel

调整后的代码

Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open('c:/temp/gab.xls', "r")
sheet = book.worksheet 4

# 获取表头行,确定需要验证的字段列索引
header_row = sheet.row(0)
# 定义需要验证的字段与界面单元格位置的映射(根据实际界面结构调整)
field_to_cell_index = {
  'leitura' => 4,    # 对应界面第4个tvCell
  'hidrometro' => 5, # 对应界面第5个tvCell
  'diametro' => 6,   # 对应界面第6个tvCell
  'lacre' => 7       # 对应界面第7个tvCell
}

# 跳过表头,从第2行开始遍历数据行(索引从1开始)
data_start_row = 1
row_offset = 2 # 界面起始行偏移

sheet.each_with_index(data_start_row) do |row, idx|
  # 跳过空行
  break if row.compact.empty?

  # 遍历需要验证的每个字段
  field_to_cell_index.each do |field, cell_pos|
    # 获取表头中该字段对应的列索引
    col_index = header_row.index(field)
    next unless col_index # 跳过不存在的字段

    expected_tooltip = row[col_index]
    next if expected_tooltip.nil?

    # 验证对应界面行和单元格的tooltip
    expect(page).to have_css("tr.tvRow:nth-child(#{row_offset + idx}) .tvCell:nth-child(#{cell_pos}) img[tooltip='#{expected_tooltip}']")
  end
end

代码调整说明

  • 先读取表头行,通过字段名定位横向表格中的列索引
  • 定义字段与界面单元格位置的映射关系,适配界面布局
  • 遍历每一行数据,对每个目标字段分别进行界面验证
  • 增加空行判断,避免无效循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:01:22