python使用xlrd实现检索excel中某列含有指定字符串记录的方法
本文实例讲述了python使用xlrd实现检索excel中某列含有指定字符串记录的方法。分享给大家供大家参考。具体分析如下:
这里利用xlrd,将excel中某列数据中,含有指定字符串的记录取出,并生成用这个字符串命名的txt文件
importos
importxlrd,sys
#inputtheexcelfile
Filename=raw_input('inputthefilename&path:')
ifnotos.path.isfile(Filename):
raiseNameError,"%sisnotavalidfilename"%Filename
#opentheexcelfile
bk=xlrd.open_workbook(Filename)
#getthesheetsnumber
shxrange=range(bk.nsheets)
printshxrange
#getthesheetsname
forxinshxrange:
p=bk.sheets()[x].name.encode('utf-8')
print"SheetsNumber(%s):%s"%(x,p.decode('utf-8'))
#inputyoursheetsname
sname=int(raw_input('choosethesheetnumber:'))
try:
sh=bk.sheets()[sname]
except:
print"nothissheet"
#returnNone
nrows=sh.nrows
ncols=sh.ncols
#returnthelinesandcolnumber
print"line:%dcol:%d"%(nrows,ncols)
#inputthecheckcolumn
columnnum=int(raw_input('whichcolumnyouwanttocheckplsinputthenum(thefirstcolnumnnumis0):'))
whilecolumnnum+1>ncols:
columnnum=int(raw_input('yournumisoutofrange,plsinputagain:'))
#inputthesearchingstringandcolumn
testin=raw_input('inputthestring:')
#findthecolsandsavetoatxt
outputfilename=testin+'.txt'
outputfile=open(outputfilename,'w')
#findtherowswhichyouwanttoselectandwritetoatxtfile
foriinrange(nrows):
cell_value=sh.cell_value(i,columnnum)
iftestininstr(cell_value):
outputs=sh.row_values(i)
fortiminoutputs:
outputfile.write('%s'%(tim))
outputfile.write('%s'%(os.linesep))
outputfile.close()
希望本文所述对大家的Python程序设计有所帮助。