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程序设计有所帮助。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短