使用 xlrd 循环访问工作表和工作簿



我是一个彻头彻尾的菜鸟。我需要从工作簿中的每个其他工作表(从第三个开始)中获取相同的单元格值,并将它们放入另一个工作表中。我继续得到一个索引错误:列出索引超出范围。工作簿中有 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

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

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)其中:

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

start:序列的起始编号。
stop:生成最多但不包括此数字的数字。
step:序列中每个数字之间的差异。

参考:Python 的 range() 参数

为了从每张纸上获取细胞,将细胞值放入循环中。

最终代码可以是:

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)以避免错误。

相关内容

最新更新