So I have a method in a class I am working on some sorting automation in openpyxl and I believe I see where the issue is, but I can't seem to get the solution out. I am sorting by value to string for a column [3] or 'D' Ascending; However after the sort it clears the blank values that exist, but I need to preserve the blank values for review for another set of methods later on.
Below is the class/method and I will identify below where I have looked into, trying to solve this but can't seem to get it to work.
class Excel:
... other methods ...
def admissions_sort(workbook_path): #sheethandle (rename)
wb = load_workbook(workbook_path)
sheet_name = "Clients" # You can change this to the desired sheet name
ws = wb[sheet_name]
data = []
for row in ws.iter_rows(min_row=3, values_only=True):
data.append(row)
def sorting_key(x): # Defines a sorting function that handles None values
value = x[3]
return (value is None, str(value)) # Convert value to string
sorted_data = sorted(data, key=sorting_key, reverse=False)
for row_idx, row in enumerate(sorted_data, start=2):
for col_idx, value in enumerate(row, start=1):
ws.cell(row=row_idx, column=col_idx, value=value)
if "Sheet1" in wb.sheetnames:
sheet_to_delete = wb["Sheet1"]
wb.remove(sheet_to_delete)
wb.save(workbook_path)
I have read the following docs:
https://openpyxl.readthedocs.io/en/latest/tutorial.html#values-only
I have scanned some entries in Stack Overflow. I couldn't find anything that 'preserved' the blanks, but of what I could dig up handled removing them, I tried to apply reverse logic, but I think I have made myself a little hole that I can't seem to understand why.
I assume in the lines:
def sorting_key(x): # Defines a sorting function that handles None values
value = x[3]
return (value is None, str(value)) # Convert value to string
return values is none, str(value) would return blank values? That is my misunderstanding, as instead it doesn't remove blanks instead it fills it with dates that don't seem to corellate with any sort of pattern or filter, or sorting method that is applied.
To this specific method it is only applied to one workbook, and is isolated to only handle this sorting method.
Made the following changes and this appears to work for this:
I apologize if I inconvenienced anyone, but having taking a second to look away and review the entire method instead of zeroing in on what I assumed the issue was, I had a second to step away and review.
I hope this helps anyone else who might come across this issue as well.
data = []
for row in ws.iter_rows(min_row=3, max_row=ws.max_row, min_col=1,
max_col=ws.max_column, values_only=True):
data.append(row)
def sorting_key(x):
value = x[3]
return (value is None, value) # remove str(value)
sorted_data = sorted(data, key=sorting_key)
for row in ws.iter_rows(min_row=3, max_row=ws.max_row, min_col=1, max_col=ws.max_column):
for cell in row:
cell.value = None