Python Openpyxl ...删除具有特定单词的行

时间:2016-02-11 18:45:20

标签: python excel openpyxl

您正在使用openpyxl模块格式化电子表格。我试图将A和B列加入","对于每一行并删除" - "在B栏的编号中 我也试图删除任何有"无"的行。在专栏中。我有第一部分,但我在删除"无"和整行。下面你会看到我的代码,然后是我想要实现的前后。我非常感谢你的帮助,因为我仍然是Python的noobie。

**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

1 个答案:

答案 0 :(得分:0)

据我所知,openpyxl中没有删除行的方法。所以请参阅下面我使用COM的地方。

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()