Python uses xlrd to retrieve records with specified strings in a column in Excel

Source: Internet
Author: User

Xlrd is used to retrieve records containing a specified string from a column of data in Excel and generate a TXT file named after this string.

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

 

 
 
Related Article

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.