Delete empty row - openpyxl
May be for someone next code will be useful:
index_row = []
# loop each row in column A
for i in range(1, ws.max_row):
# define emptiness of cell
if ws.cell(i, 1).value is None:
# collect indexes of rows
index_row.append(i)
# loop each index value
for row_del in range(len(index_row)):
ws.delete_rows(idx=index_row[row_del], amount=1)
# exclude offset of rows through each iteration
index_row = list(map(lambda k: k - 1, index_row))
2018 update: I was searching how to delete a row today and found that the functionality is added in openpyxl 2.5.0-b2. Just tried and it worked perfectly. Here's the link where I found the answer: https://bitbucket.org/openpyxl/openpyxl/issues/964/delete_rows-does-not-work-on-deleting
And here's the syntax to delete one row:
ws.delete_rows(index, 1)
where: 'ws' is the worksheet, 'index' is the row number, and '1' is the number of rows to delete.
There's also the ability to delete columns, but I haven't tried that.
As far as I know openpyxl provides no way to delete rows. You may use COM instead, e.g.:
import win32com.client
filename = 'c:/my_file.xlsx'
sheetname = 'Sheet1'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.Workbooks.Open(Filename=filename)
ws = wb.Sheets(sheetname)
begrow = 1
endrow = ws.UsedRange.Rows.Count
for row in range(begrow,endrow+1): # just an example
if ws.Range('A{}'.format(row)).Value is None:
ws.Range('A{}'.format(row)).EntireRow.Delete(Shift=-4162) # shift up
wb.Save()
wb.Close()
xl.Quit()