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



 

 
目录
相关文章
|
10天前
|
存储 数据挖掘 Python
使用Python集合高效统计Excel数据
使用Python集合高效统计Excel数据
28 7
|
7天前
|
存储 索引 Python
字符串、列表、元组、字典(python)
字符串、列表、元组、字典(python)
|
10天前
|
数据采集 开发者 Python
在Python中判断字符串中是否包含字母
在Python中判断字符串中是否包含字母
23 4
|
9天前
|
Python
python之字符串定义、切片、连接、重复、遍历、字符串方法
python之字符串定义、切片、连接、重复、遍历、字符串方法
9 0
python之字符串定义、切片、连接、重复、遍历、字符串方法
|
16天前
|
API Python
Python库`openpyxl`是一个用于读取和写入Excel 2010 xlsx/xlsm/xltx/xltm文件的库。
【6月更文挑战第19天】`openpyxl`是Python处理xlsx文件的库,支持读写Excel 2010格式。使用`pip install openpyxl`安装。基本操作包括加载文件、读写单元格、操作行和列。例如,加载Excel后,可以读取单元格`A1`的值,或将“Hello, World!”写入`A1`。还可修改单元格内容,如加1后保存到新文件。更多功能,如样式和公式,见官方文档[1]。 [1]: <https://openpyxl.readthedocs.io/en/stable/>
38 1
|
16天前
|
Python
【干货】python xlwt写入excel操作
【干货】python xlwt写入excel操作
12 2
|
1天前
|
存储 Python
语音输入,python数据类型,type()用来查看数据类型,数据类型转换,int(x)转整数,float(x)转换为浮点数,str(x),将对象转为字符串,标识符,标识符不允许使用关键字,关键字参考
语音输入,python数据类型,type()用来查看数据类型,数据类型转换,int(x)转整数,float(x)转换为浮点数,str(x),将对象转为字符串,标识符,标识符不允许使用关键字,关键字参考
Python----统计字符串中的英文字母、空格、数字和其它字符的个数。
Python----统计字符串中的英文字母、空格、数字和其它字符的个数。
python---将随机输入的时间格式字符串进行转换
python---将随机输入的时间格式字符串进行转换
|
8天前
|
索引 Python 容器
深入探索Python字符串:技巧、方法与实战
深入探索Python字符串:技巧、方法与实战