Python uses XLRD to retrieve a column in Excel that contains a specified string record

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.