I need to remove some rows in an simple and straight-forward Excel file.
For example, to remove the rows that column B is not blank.
What I can think of is not really a ‘remove’ way, but rename a new created file:
import os
import xlwt
from xlrd import open_workbook
old_file = open_workbook('C:\\file.xls',formatting_info=True)
old_sheet = old_file.sheet_by_index(0)
new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True)
contents = []
for row in range(old_sheet.nrows):
a = old_sheet.cell(row,0).value
b = old_sheet.cell(row,1).value
if len(b) < 1:
contents.append(a)
for c, content in enumerate(contents):
new_sheet.write(c, 0, content)
new_file.save('C:\\file_1.xls')
os.remove('C:\\file.xls')
os.rename('C:\\file_1.xls', 'C:\\file.xls')
Well, it’s not really deleting the rows but anyhow it could be a suitable way.
What better ways are there to do this, such as considering more conditions?