'How I can only print the visible cells (filtered) in a column with openpyxl

I am working with a excel sheet and want to print only the value of cells which are visible in a particular column. Below is the example, I'm expecting it to print as second image but it is printing all the values Excel_Example enter image description here

This is filtered as below enter image description here

below is my code

import openpyxl
import warnings

warnings.filterwarnings("ignore", category=DeprecationWarning)

excel_file_path_source = r'C:\Users\User\PycharmProjects\Test\demo.xlsx'
workbook_object = openpyxl.load_workbook(excel_file_path_source)
sheet_obj = workbook_object.get_sheet_by_name('Sheet1')

no_of_rows = sheet_obj.max_row
for i in range(2, no_of_rows+1):
    cell_obj = sheet_obj.cell(row=i, column=1)
    cell_obj_value = cell_obj.value
    if cell_obj_value is not None:
        print(cell_obj_value)

enter image description here



Solution 1:[1]

You can use the below code to achieve what you are looking for.... Note that I have given code for both printing the data as well as writing the filtered data to a dataframe df in case you want to use the data for further processing

from openpyxl import load_workbook

wb = load_workbook('input.xlsx') # use your workbook path
ws = wb['Sheet5'] # change to your excel sheet name
df = pd.DataFrame(columns = ['FnD','Date','Time'])

# iterate over all the rows in the sheet
for row in ws:
    # use if it has not been hidden
    if ws.row_dimensions[row[0].row].hidden == False:
        print(row[0].value, row[1].value, row[2].value) 
        if row[0].value != "FnD": #Ignore if header, else, write to DataFrame
            df.loc[len(df.index)] = [row[0].value, row[1].value, row[2].value] 

My UNFILTERED input Excel sheet

enter image description here

My FILTERED input Excel sheet

enter image description here

Output

FnD Date Time
1121 2001-01-01 00:00:00 00:00:01
1122 2002-01-01 00:00:00 00:00:01
1123 2003-01-01 00:00:00 00:00:01
1124 2004-01-01 00:00:00 00:00:01

>>df
    FnD Date    Time
0   1121    2001-01-01  00:00:01
1   1122    2002-01-01  00:00:01
2   1123    2003-01-01  00:00:01
3   1124    2004-01-01  00:00:01

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Redox