简体   繁体   中英

Python Openpyxl…remove rows that have a specific word

Hi working with the openpyxl module to format a spreadsheet. I'm trying to join column A and B with a "," for each row and remove the "-" in the numbers of column B. I'm also trying to remove any row that has "None" in the column. I have the first part down, but I'm having trouble removing "None" and the entire row. Below you will see my code followed by the before and after of what I'm looking to achieve. I would greatly appreciate your help as I'm still a noobie at Python.

**Code**

import openpyxl

wb = openpyxl.load_workbook('Users.xlsx')

sheet = wb.get_active_sheet()

for rows in sheet['A3':'B11']:
    try:
        print(rows[0].value + "," + rows[1].value.replace("-",""))
    # TODO: remove rows with the word "None"
    except:
        if rows == "None":
            rows[0].value.delete
            continue

**Before**

b0119xxx    None
b0105xxx    534-0498
c0215xxx    534-0498
c0245xxx    None
d0232xxx    534-0498
d0263xxx    534-0498
d0190xxx    534-0498
d0085xxx    None
g0009xxx    534-0498
g0169xxx    534-0498
g0221xxx    534-0498

**After**

 b0105xxx,5340498
 c0215xxx,5340498
 d0232xxx,5340498
 d0263xxx,5340498
 d0190xxx,5340498
 g0009xxx,5340498
 g0169xxx,5340498
 g0221xxx,5340498

As far as I can tell there exists no method in openpyxl to delete a row. So see below where I use COM to do so.

import openpyxl

filename = 'Users.xlsx'
sheetname = 'Sheet1'

wb = openpyxl.load_workbook(filename)
sheet = wb.get_sheet_by_name(sheetname)
for rows in sheet['A3':'B11']:
  if rows[1].value == 'None':
    rows[0].value = None 
    rows[1].value = None
  else:
    rows[0].value = rows[0].value + "," + rows[1].value.replace("-","") 
    rows[1].value = None

wb.save(filename)


import win32com.client

xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.Workbooks.Open(Filename=filename) 
sheet = wb.Sheets(sheetname)
for row in range(3,12):
  if sheet.Range('A{}'.format(row)).Value is None:
    sheet.Range('A{}'.format(row)).EntireRow.Delete(Shift=-4162)

wb.Save()
wb.Close()
xl.Quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM