Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter column data using openpyxl

I am trying to apply a filter to an existing Excel file, and export it to another Excel file. I would like to extract rows that only contain the value 16, then export the table to another excel file (as shown in the picture below).

I have tried reading the openpyxl documentation multiple times and googling for solutions but I still can't make my code work. I have also attached the code and files below

import openpyxl
# Is use to create a reference of the Excel to wb
 wb1 = openpyxl.load_workbook('test_data.xlsx')
 wb2 = openpyxl.load_workbook('test_data_2.xlsx')

# Refrence the workbook to the worksheets
 sh1 = wb1["data_set_1"]
 sh2 = wb2["Sheet1"]

 sh1.auto_filter.ref = "A:A"
 sh1.auto_filter.add_filter_column(0, ["16"])
 sh1.auto_filter.add_sort_condition("B2:D6")

 sh1_row_number = sh1.max_row
 sh1_col_number = sh1.max_column

 rangeSelected = []
 for i in range(1, sh1_row_number+1, 1):
     rowSelected = []
     for j in range(1, sh1_col_number+1, 1):
         rowSelected.append(sh1.cell(row = i, column = j))
     rangeSelected.append(rowSelected)

  del rowSelected

 for i in range(1, sh1_row_number+1, 1):
    for j in range(1, sh1_col_number+1, 1):
        sh2.cell(row = i, column = j).value = rangeSelected[i-1][j-1].value

 wb1.save("test_data.xlsx")
 wb2.save("test_data_2.xlsx")

The pictures shows what should be the desire result

like image 846
The Confused Programmer Avatar asked Apr 11 '26 12:04

The Confused Programmer


1 Answers

The auto filter doesn't actually filter the data, it is just for visualization. You probably want to filter while looping through the workbook. Please note with this code I assume you have the table headers already in the second workbook. It does not overwrite the data, it appends to the table.

import openpyxl
# Is use to create a reference of the Excel to wb
wb1 = openpyxl.load_workbook('test_data.xlsx')
wb2 = openpyxl.load_workbook('test_data_2.xlsx')

# Refrence the workbook to the worksheets
sh1 = wb1["data_set_1"]
sh2 = wb2["data_set_1"]   # use same sheet name, different workbook

for row in sh1.iter_rows():
    if row[0].value == 16:   # filter on first column with value 16
        sh2.append((cell.value for cell in row))     

wb1.save("test_data.xlsx")
wb2.save("test_data_2.xlsx")
like image 195
PythonSherpa Avatar answered Apr 14 '26 02:04

PythonSherpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!