Skip to main content
 首页 » 编程设计

Python/xlrd 读取行和列

2025年05月04日20虾米哥

我有特定结构的 exel 文件。 第一行是标题,第二行是名称,最后一行是值。 我只需要标题和值,如果 Excel 文件只有 3 行,这并不难,但它可以是 100 行和列,我只需要获取标题和值,而不是任何名称和空行

         1          2        3            
1    GroupOne     Empty      Empty 
2      Jonh       Elena     Mike     
3        45         100      500  
4        Empty      Empty     Empty 
5   GroupTwo       Empty     Empty 
6   Lisa           Ken       Lui 
7   100             300      400 

等等

如您所见,两个标题之间始终是一个空行。 最后它会是这样的:

GroupOne 
45   100   500 
GroupTwo 
100 300 400 

提前致谢。如果能提供一些帮助,我将不胜感激

请您参考如下方法:

我觉得这个website有一个例子可以帮助你:

import xlrd 
workbook = xlrd.open_workbook('my_workbook.xls') 
worksheet = workbook.sheet_by_name('Sheet1') 
num_rows = worksheet.nrows - 1 
num_cells = worksheet.ncols - 1 
curr_row = -1 
while curr_row < num_rows: 
  curr_row += 1 
  row = worksheet.row(curr_row) 
  print 'Row:', curr_row 
  curr_cell = -1 
  while curr_cell < num_cells: 
    curr_cell += 1 
    # Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank 
    cell_type = worksheet.cell_type(curr_row, curr_cell) 
    cell_value = worksheet.cell_value(curr_row, curr_cell) 
    print ' ', cell_type, ':', cell_value 

cell_type 函数应该可以帮助您构建一个 if 语句,例如 if worksheet.cell_type != 0,从而跳过空单元格。