Quantcast
Viewing all articles
Browse latest Browse all 1268

Python • Sort data in Excel

Hi.

I have a excel file where I add data in. I want to sort the data on the first column, so all other cells are changed too. I have tried to fix it by using the below code, but I don't think it is working as it should because when I open the excel I can see the date in columns are changed to have both date and time. Is there no easy way to do a sort and the save the file with out read it all and then add it again or I'm I doing this wrong?

Code:

from openpyxl import load_workbookdef main(file_path, search_value):    # Load data into a list of lists    data = []    for row in ws.iter_rows(min_row=2, max_row=ws.max_row, min_col=1, max_col=ws.max_column):        row_data = [cell.value for cell in row]        data.append(row_data)    # Sort data based on the first column    sorted_data = sorted(data, key=lambda x: x[0])    # Rewrite sorted data to worksheet    for row_index, row_data in enumerate(sorted_data, start=2):        for column_index, value in enumerate(row_data, start=1):            ws.cell(row=row_index, column=column_index, value=value)    # Save the workbook    wb.save(file_path)  

Statistics: Posted by valnurat — Fri Mar 01, 2024 11:35 am



Viewing all articles
Browse latest Browse all 1268

Trending Articles