当前位置: 首页 > 编程笔记 >

python使用xlrd实现检索excel中某列含有指定字符串记录的方法

弘承运
2023-03-14
本文向大家介绍python使用xlrd实现检索excel中某列含有指定字符串记录的方法,包括了python使用xlrd实现检索excel中某列含有指定字符串记录的方法的使用技巧和注意事项,需要的朋友参考一下

本文实例讲述了python使用xlrd实现检索excel中某列含有指定字符串记录的方法。分享给大家供大家参考。具体分析如下:

这里利用xlrd,将excel中某列数据中,含有指定字符串的记录取出,并生成用这个字符串命名的txt文件

import os
import xlrd,sys
# input the excel file
Filename=raw_input('input the file name&path:')
if not os.path.isfile(Filename):
  raise NameError,"%s is not a valid filename"%Filename
#open the excel file
bk=xlrd.open_workbook(Filename)
#get the sheets number
shxrange=range(bk.nsheets)
print shxrange
#get the sheets name
for x in shxrange:
  p=bk.sheets()[x].name.encode('utf-8')
  print "Sheets Number(%s): %s" %(x,p.decode('utf-8'))
# input your sheets name
sname=int(raw_input('choose the sheet number:'))
try:
  sh=bk.sheets()[sname]
except:
  print "no this sheet"
  #return None
nrows=sh.nrows
ncols=sh.ncols
# return the lines and col number
print "line:%d col:%d" %(nrows,ncols)
#input the check column
columnnum=int(raw_input('which column you want to check pls input the num(the first colnumn num is 0):'))
while columnnum+1>ncols:
  columnnum=int(raw_input('your num is out of range,pls input again:'))
# input the searching string and column
testin=raw_input('input the string:')
#find the cols and save to a txt
outputfilename=testin + '.txt'
outputfile=open(outputfilename,'w')
#find the rows which you want to select and write to a txt file
for i in range(nrows):
  cell_value=sh.cell_value(i, columnnum)
  if testin in str(cell_value):
    outputs=sh.row_values(i)
    for tim in outputs:
      outputfile.write('%s  ' %(tim))
    outputfile.write('%s' %(os.linesep)) 
outputfile.close()

希望本文所述对大家的Python程序设计有所帮助。

 类似资料:
  • rank ▲ ✰ vote url 24 644 117 879 url Python中有检查字符串包含的方法吗? 我正在找string.contains或者string.indexof方法. 我希望: if not somestring.contains("blah"): continue 你可以用in啊: if not "blah" in somestring: continue 或

  • 本文向大家介绍JS判断字符串变量是否含有某个字串的实现方法,包括了JS判断字符串变量是否含有某个字串的实现方法的使用技巧和注意事项,需要的朋友参考一下 JS判断字符串变量是否含有某个字串的实现方法 indexOf用法: 返回 String 对象内第一次出现子字符串的字符位置。 strObj.indexOf(subString[, startIndex]) 参数 strObj 必选项。String

  • 同 find() 方法类似,index() 方法也可以用于检索是否包含指定的字符串,不同之处在于,当指定的字符串不存在时,index() 方法会抛出异常。 index() 方法的语法格式如下: str.index(sub[,start[,end]]) 此格式中各参数的含义分别是: str:表示原字符串; sub:表示要检索的子字符串; start:表示检索开始的起始位置,如果不指定,默认从头开始检

  • find() 方法用于检索字符串中是否包含目标字符串,如果包含,则返回第一次出现该字符串的索引;反之,则返回 -1。 find() 方法的语法格式如下: str.find(sub[,start[,end]]) 此格式中各参数的含义如下: str:表示原字符串; sub:表示要检索的目标字符串; start:表示开始检索的起始位置。如果不指定,则默认从头开始检索; end:表示结束检索的结束位置。如

  • 我的问题 当我搜索时,它会按要求返回,但当我搜索时,它会返回,为什么会出现这种情况,以及如何修复它?