openpyxl: filter for variable in specified column

Viewed 21

In each row, I want to filter for the value "TRUE" in column 8. If that row contains "TRUE" in that column, I want to copy that row to another sheet. Is there a way to do this using openpyxl?

#Filter for rows containing TRUE
from openpyxl import Workbook
from openpyxl import load_workbook
import glob

wb1 = openpyxl.load_workbook('DataSource.xlsx') #Source 
wb2 = openpyxl.load_workbook('DataTarget.xlsx') #Target

# Refrence the workbook to the worksheets
sh1 = wb1["sheet 1"] #Source
sh2 = wb2["sheet 2"] #Target   
min_col, min_row, max_col, max_row = range_boundaries("A:I")

for row in sh1.iter_rows():
    if row[8].value == "TRUE":  
        sh2.append((cell.value for cell in row[min_col-1:max_col]))     

wb2.save("Filter Test.xlsx")
1 Answers

This is how you properly read and write data using openpyxl().

note that the columns start at 0 (so column 1 is index 0).

#Filter for rows containing TRUE
from openpyxl import Workbook
from openpyxl import load_workbook

source = "C:\\test\\DataSource.xlsx"
target = "C:\\test\\DataTarget.xlsx"
wb1 = load_workbook(source) #Source 
wb2 = load_workbook(target) #Target

# Refrence the workbook to the worksheets
sh1 = wb1["Sheet1"] #Source
sh2 = wb2["Sheet2"] #Target   

for row in sh1.iter_rows():
    if row[7].value == True:
        # whatever you want to do  
        sh2.append([1,2,3])

wb2.save("C:\\test\\Filter Test.xlsx")

print('done')
Related