python利用xlrd完成excel中某列检索含有指定字符串的记录

简介: 利用xlrd,将excel中某列数据中,含有指定字符串的记录取出,并生成用这个字符串命名的txt文件 import osimport xlrd,sys# input the excel fileFilename=raw_input('input the file name&path:')if not os.

 利用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()



 

 
目录
相关文章
|
11月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
563 100
|
11月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
664 99
|
11月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
11月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
11月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
11月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
533 0
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
12月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
526 92

推荐镜像

更多