How to import filtered excel table into python?

后端 未结 1 1504
忘了有多久
忘了有多久 2020-12-11 10:24

I have an excel table, it looks like

Then, I created a filter on the column Sex to get all the female data, it looks like:

Then, I want to

相关标签:
1条回答
  • 2020-12-11 10:46

    As mentioned earlier in comments, a very quick and dirty way to do the trick is copying your filtered data in a new Excel file (without any filter) and get data from such a file.

    A more elegant and complete solution consists in using openpyxl to read filtered data.

    First, install openpyxl

    $ pip install openpyxl
    

    Then, use a script like this one to read just visible data:

    from openpyxl import load_workbook
    
    wb = load_workbook('foo.xlsx') # use the actual path of your workbook
    ws = wb['Bar'] # use your sheet name instead of Bar
    
    # iterate over all the rows in the sheet
    for row in ws: 
        # use the row only if it has not been filtered out (i.e., it's not hidden)
        if ws.row_dimensions[row[0].row].hidden == False:
            print row # ...or do what you need
    

    Note that row is a tuple of Cells. Use the attribute value for accessing to each cell's value:

        if ws.row_dimensions[row[0].row].hidden == False:
            for cell in row:
                print cell.value 
    

    You can use that logic to get your values straight from the original filtered file.

    PS: openpyxl provides also a cool Pandas integration out of the box.

    0 讨论(0)
提交回复
热议问题