Python Forum
Delete a whole row if all cells contain certain values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete a whole row if all cells contain certain values
#1
Hello !

I try to delete all rows from a Excel sheet, who satisfied this condition: all cells from a row must contain only the values "-" or "".

I use Python and openpyxl .

But my code, don't work well:

import openpyxl

wb1 = openpyxl.load_workbook(filename="testat_openpyxl.xlsx")

instr=""
for i in range(5, wb1["Centralizator"].max_row):

  for j in range(7,49):


    celval=wb1["Centralizator"].cell(row=i,column=j).value
    ins='{}=="-" or {}=="" and '.format(celval)
    instr=instr + ins
 if  instr[:-3]:

    wb1["Centralizator"].delete_rows(i,1)


wb1.save('testat_openpyxl.xlsx')
My idea is to create a big "if" statement , to check all cells from a row:

if wb1["Centralizator"].cell(row=5,column=7).value=="-" or 
wb1["Centralizator"].cell(row=5,column=7).value=="" and
wb1["Centralizator"].cell(row=5,column=8).value=="-" or
wb1["Centralizator"].cell(row=5,column=8).value==""
wb1["Centralizator"].cell(row=5,column=9).value=="-" or
wb1["Centralizator"].cell(row=5,column=9).value==""
.........loop until column 48............
wb1["Centralizator"].cell(row=5,column=48).value=="-" or
wb1["Centralizator"].cell(row=5,column=48).value==""
now jump to next row
if wb1["Centralizator"].cell(row=6,column=7).value=="-" or 
wb1["Centralizator"].cell(row=6,column=7).value=="" and
wb1["Centralizator"].cell(row=6,column=8).value=="-" or
wb1["Centralizator"].cell(row=6,column=8).value==""
.........loop until column 48...........
wb1["Centralizator"].cell(row=6,column=48).value=="-" or
wb1["Centralizator"].cell(row=6,column=48).value==""
next row.......until max_row....
Reply
#2
you need to check/delete rows starting from last row and going up (or down - depending on how you look at it) to 1st
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Openpyxl-change value of cells in column based on value that currently occupies cells phillipaj1391 5 9,789 Mar-30-2022, 11:05 PM
Last Post: Pedroski55
  How can I iterate through all cells in a column (with merge cells) with openpyxl? aquerci 1 7,504 Feb-11-2021, 09:31 PM
Last Post: nilamo
  Copy certain cells into new workbook certain cells Kristenl2784 4 2,483 Jul-14-2020, 07:59 PM
Last Post: Kristenl2784

Forum Jump:

User Panel Messages

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