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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

举例讲解Python设计模式编程中对抽象工厂模式的运用

举例讲解Python设计模式编程中对抽象工厂模式的运用

抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 优点:易于交换“产品系列”,只要更改相应的工厂即可。 缺点:建立产品的时候很繁琐,需要增加和修改很多东...

Python自定义一个类实现字典dict功能的方法

如下所示: import collections class Mydict(collections.UserDict): def __missing__(self, ke...

python三元运算符实现方法

这是今天在温习lambda表达式的时候想到的问题,众所周知C系列语言中的 三元运算符(?:)是一个非常好用的语句, 关于C中的三元运算符 表达式1?表达式2:表达式3 那么在python...

Python简明入门教程

本文实例讲述了Python简明入门教程。分享给大家供大家参考。具体如下: 一、基本概念 1、数 在Python中有4种类型的数——整数、长整数、浮点数和复数。 (1)2是一个整数的例子。...

python正则表达式匹配不包含某几个字符的字符串方法

一、匹配目标 文件中所有以https?://开头,以.jpg|.png|.jpeg结尾的字符串 二、尝试过程 1)        自然想到...