[英]Searching Excel
I have a script that searches each row of an Excel document until it finds an empty row. 我有一个脚本,可以搜索Excel文档的每一行,直到找到一个空行。 My issue is i cant get it to move down the rows without calling the function the correct amount of times to reach an empty row (which defeats the purpose of the script).
我的问题是,我无法让它向下移动而没有调用函数达到空行的正确时间(这违反了脚本的目的)。 When I tried to make the Excel search function loop within itself I keep getting an IndexError.
当我尝试使Excel搜索功能在自身内部循环时,我不断收到IndexError。 I tried to create another function outside the original function based on boolean values of global variables but had the same issues (hence the incomplete and the empty variables) Could someone please help me figure out what I'm doing wrong?
我试图根据全局变量的布尔值在原始函数之外创建另一个函数,但是遇到了同样的问题(因此存在不完整和空变量)有人可以帮我弄清楚我在做什么错吗?
import xlrd
workbook = xlrd.open_workbook( 'example.xls' )
sheet_names = workbook.sheet_names()
global incomplete
global empty
global nextrow
global counter
incomplete = False
empty = False
counter = 0
def excelreader():
for sheet_name in sheet_names:
sheet = workbook.sheet_by_name( 'A Test Sheet')
global counter
try:
row_values = sheet.row_values(counter)
counter += 1
if '' in row_values:
global incomplete
incomplete = True
print incomplete
except IndexError:
print'IndexError'
def exceliterator():
if incomplete is False:
excelreader()
excelreader()
excelreader()
excelreader()
You does not need exception or function definition to exit from loop. 您不需要异常或函数定义即可退出循环。 Simplest way: keyword
break
: 最简单的方法:关键字
break
:
import xlrd
workbook = xlrd.open_workbook( 'test.xls' )
sheet_names = workbook.sheet_names()
incomplete_line = False
for sheet_name in sheet_names:
sheet = workbook.sheet_by_name(sheet_name)
for row_idx in range(0, sheet.nrows):
row_values = sheet.row_values(row_idx)
if '' in row_values:
print "Incomplete line in sheet", sheet_name, "at line", row_idx+1
incomplete_line = True
break
if incomplete_line:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.