使用xlrd迭代工作表和工作簿

时间:2017-03-15 20:06:44

标签: excel python-2.7

我是一个总菜鸟。我需要从工作簿中的每个其他工作表(从第三个开始)获取相同的单元格值,并将它们放入另一个工作簿中。我继续得到一个IndexError:list index超出范围。工作簿中有20张。我导入了xlrd和xlwt。

代码:

sheet_id = 3
output = 0
cellval = enso.sheet_by_index(sheet_id).cell(20,2).value


sheet_cp = book_cp.get_sheet(output)
sheet_cp.write(1, 1, cellval)

    book_cp.save(path)
for sheet_id in range(0,20):
    sheet_enso = enso_cp.get_sheet(sheet)
    sheet_cp = book_cp.get_sheet(output)
    sheet_cp.write(1, 1, cellval)
    sheet_id = sheet_id + 2
    output = output + 1

1 个答案:

答案 0 :(得分:1)

您的问题很可能存在于此处:

sheet_id = 3
cellval = enso.sheet_by_index(sheet_id).cell(20,2).value # row:20, column:0

检查以下内容:
1 - 确保sheet_id=3符合您的要求(工作表索引从0开始),因此第3张工作表索引= 2,除非您需要第4张工作表。
2 - 检查所选工作表中是否存在cell(20,0)(其中单元格(0,0)是第一个单元格)。

另外,您无需定义sheet_id
而是将范围改为(2:第3张,21:20张)> in range(2,21)其中:

  

范围([开始],停止[,步骤])

     

开始:序列的起始编号   停止:生成最多但不包括此数字的数字。
  步骤:序列中每个数字之间的差异。

参考:Python's range() Parameters

并从每个工作表中获取cellval,将cellval放入循环中。

最终代码可以是:

output = 0
for sheet_id in range(2,21): # (starting at the 3rd sheet (index=2), stopping at 20 "21 not included")
    cellval = enso.sheet_by_index(sheet_id).cell(20,0).value # row 20, column 0
    #sheet_enso = enso_cp.get_sheet(sheet) # i don't know if you need that for something else
    sheet_cp = book_cp.get_sheet(output)
    sheet_cp.write(1, 1, cellval)
    output = output + 1
book_cp.save(path)

再次检查所有源表中是否存在cell(20,0)以避免错误。