After spending the last few hours trying to find a way to do this, I've decided to just ask.
I've gone through the openpyxl docs more than a few times, as well as going through the questions asked here and here, and even the chapter from this online book, and none of it really answers what I'm attempting to do.
Here's the code I have right now:
for row in ws.iter_rows():
i = 1
if row[i].internal_value() == None:
ws.Rows(i).Delete()
else:
i + 1
I've tried many different things with this, and right now I'm getting an error:
TypeError: 'NoneType' object is not callable
What am I doing wrong, and how can I fix it so that I'm iterating over all of the rows and deleting any that either are completely empty, or (if it's easier to implement) have an empty first cell?
Thanks
Algorithm (Steps) Create a variable to store the path of the input excel file. To create/load a workbook, pass the input excel file as an argument to the openpyxl module's load_workbook() function (loads a workbook). Access the specific sheet of the workbook by giving the sheet name as the index to the workbook object.
To delete rows and columns from DataFrames, Pandas uses the “drop” function. To delete a column, or multiple columns, use the name of the column(s), and specify the “axis” as 1. Alternatively, as in the example below, the 'columns' parameter has been added in Pandas which cuts out the need for 'axis'.
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))
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With