正在搜索 Excel
Searching Excel
我有一个脚本可以搜索 Excel 文档的每一行,直到找到一个空行。我的问题是我无法在不调用函数正确次数以到达空行的情况下向下移动行(这违背了脚本的目的)。当我试图使 Excel 搜索函数在其内部循环时,我不断收到 IndexError。我试图根据全局变量的布尔值在原始函数之外创建另一个函数,但遇到了同样的问题(因此不完整和空变量)有人可以帮我弄清楚我做错了什么吗?
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()
您不需要异常或函数定义来退出循环。最简单的方式:关键字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
我有一个脚本可以搜索 Excel 文档的每一行,直到找到一个空行。我的问题是我无法在不调用函数正确次数以到达空行的情况下向下移动行(这违背了脚本的目的)。当我试图使 Excel 搜索函数在其内部循环时,我不断收到 IndexError。我试图根据全局变量的布尔值在原始函数之外创建另一个函数,但遇到了同样的问题(因此不完整和空变量)有人可以帮我弄清楚我做错了什么吗?
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()
您不需要异常或函数定义来退出循环。最简单的方式:关键字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