0

I want to make a filter or exception in my code for the excel file. I have this table in excel

enter image description here

But in my result I only want the Machine 'S9401-1', how can I Get this.

This is my code

import xlrd

 #First open the workbook
wb = xlrd.open_workbook('Book1.xlsx')

 #Then select the sheet. Replace the sheet1 with name of your sheet
sheet = wb.sheet_by_name('connx 94')

 #Then get values of each column. Excuse first item which is header

machine = sheet.cell_value(1,0)
alid = sheet.cell_value(1,1)
descripcion = sheet.cell_value(1,3)
result=[machine,alid,descripcion]
print (result)
4
  • xlrd package can't apply a filter, it's designed to read Excel files and has very limited functionality in that regard. I am certain you can do this with win32com which exposes the full Excel object model (or nearly so) to apply a filter, or you could return the full dataset to a list object in python and remove the elements that don't match your criteria. Commented Jan 25, 2017 at 18:34
  • 1
    You could simply add a condtion to check for 'S9401-1' in your python code. Or you could consider using openpyxl (openpyxl.readthedocs.io/en/default/filters.html) Commented Jan 25, 2017 at 18:35
  • Have you had a chance to try my suggested answer, below? This seems to work when I have tested it. Commented Jan 26, 2017 at 0:15
  • @DavidZemens Your answer is correct and I can use for another things. Commented Jan 26, 2017 at 14:18

1 Answer 1

1

Using only xlrd package, you could do brute force like this:

import xlrd
wb = xlrd.open_workbook(r'c:\debug\py.xlsx')
sheet = wb.sheet_by_name('Sheet1')
def filterdata(sh,ID):
    vals = sh.row_values
    data = [[vals(r,0)[1], vals(r,0)[3]] for r in range(sh.nrows) if vals(r,0)[0] == ID]
    return data

print(filterdata(sheet,'S9401-1))

Making a function call, you can use different IDs:

print(filterdata(sheet,'S9401-1'))
print(filterdata(sheet,'S9401-3'))  # should return an empty list
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.