This example describes how Python uses the XLRD implementation to retrieve a column in Excel that contains a specified string record. Share to everyone for your reference. The specific analysis is as follows:
Here, we use XLRD to fetch the records in a column of Excel that contain the specified string, and generate a TXT file named with this string.
Import osimport xlrd,sys# input the Excel filefilename=raw_input (' Input the file Name&path: ') if not os.path.isfile (Fi Lename): Raise Nameerror, "%s is not a valid filename"%filename#open the Excel filebk=xlrd.open_workbook (filename) #get the Sheets Numbershxrange=range (bk.nsheets) print Shxrange#get The sheets namefor x in Shxrange:p=bk.sheets () [X].name.encod E (' utf-8 ') print "Sheets number (%s):%s"% (X,p.decode (' Utf-8 ')) # input your Sheets namesname=int (raw_input (' Choose the sh Try:sh=bk.sheets () [sname]except:print "No This sheet" #return nonenrows=sh.nrowsncols=sh.ncols# return The lines and Col numberprint "line:%d col:%d"% (nrows,ncols) #input the check Columncolumnnum=int (Raw_input (' which column You want to check pls input the num (the first colnumn num was 0): ') while Columnnum+1>ncols:columnnum=int (Raw_input (' Your num is out of RANGE,PLS input again: ') # input the searching string and columntestin=raw_input (' Input the string: ') #f IND the cols and save to aTxtoutputfilename=testin + '. txt ' outputfile=open (outputfilename, ' W ') #find the rows which you want to select and write to a TXT filefor i in range (nrows): Cell_value=sh.cell_value (i, columnnum) if testin in Str (cell_value): Outputs=sh.row_v Alues (i) for Tim in Outputs:outputfile.write ('%s '% (Tim)) Outputfile.write ('%s '% (OS.LINESEP)) outputfile.cl OSE ()
Hopefully this article will help you with Python programming.