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()
复制代码



 

  
posted @   小五义  阅读(9872)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示