Python Forum
help with an exercise
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with an exercise
#6
Change to this and see if it is better.
Take look at what zip do,then will understand the loop better.
import openpyxl
from openpyxl.styles import PatternFill

datafile1 = openpyxl.load_workbook('test1.xlsx')
fill_style1 = PatternFill(start_color='FDD835', end_color='FDD835', fill_type='solid')
fill_style2 = PatternFill(start_color='cc0000', end_color='cc0000', fill_type='solid')
data_sheet1 = datafile1['Sheet1']
data_sheet2 = datafile1['Sheet2']

# Create a new sheet for comparison results
comparison_sheet = datafile1.create_sheet('Comparison Results')

# Iterate through rows in both sheets and compare values
for row1, row2 in zip(
    data_sheet1.iter_rows(min_row=1, max_row=data_sheet1.max_row),
    data_sheet2.iter_rows(min_row=1, max_row=data_sheet2.max_row),
):
    for cell1, cell2 in zip(row1, row2):
        if cell1.value == cell2.value:
            comparison_sheet.cell(row=cell1.row, column=cell1.column, value=1).fill = fill_style1
        else:
            comparison_sheet.cell(row=cell1.row, column=cell1.column, value=0).fill = fill_style2

datafile1.save('compared_file.xlsx')
Reply


Messages In This Thread
help with an exercise - by iiiik - Aug-21-2023, 02:33 PM
RE: help with an exercise - by jefsummers - Aug-21-2023, 05:33 PM
RE: help with an exercise - by iiiik - Aug-21-2023, 05:46 PM
RE: help with an exercise - by snippsat - Aug-21-2023, 06:16 PM
RE: help with an exercise - by iiiik - Aug-21-2023, 06:45 PM
RE: help with an exercise - by snippsat - Aug-21-2023, 07:15 PM
RE: help with an exercise - by iiiik - Aug-21-2023, 07:40 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020