python使用xlrd实现检索excel中某列含有指定字符串记录的方法
admin
2023-07-31 02:21:20
0

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

相关内容

热门资讯

500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
python查找阿姆斯特朗数 题目解释 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 例如1^3 + 5...
Apache Doris 2.... 亲爱的社区小伙伴们,我们很高兴地向大家宣布,Apache Doris 2.0.0 版本已于...