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



 

 
目录
相关文章
|
6天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
178 99
|
9天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
9天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
9天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
20天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
1月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
208 92
|
1月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
185 0
|
1月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
2月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
261 0

推荐镜像

更多