Nov-08-2023, 08:15 AM
This link from the openpyxl docs should help you understand inserting rows
This below may give you some ideas. I think you want the latest data saved at the top of the XL file.
As my XL file has headers, that would be row 2.
This below may give you some ideas. I think you want the latest data saved at the top of the XL file.
As my XL file has headers, that would be row 2.
import openpyxl from datetime import datetime # this XL has 1 sheet called test path2XL = '/home/pedro/myPython/openpyxl/xlsx_files/test_file_simple.xlsx' wb = openpyxl.load_workbook(path2XL) #maxRow = wb['test'].max_row maxCol = wb['test'].max_column # show the headers for i in range(1, maxCol + 1): print('The column headers are: ', wb['test'].cell(row=1, column=i).value) # row 1 is presumably the headers so insert a row at 2 to put the latest data in row 2 """ from here put all this in a loop """ wb['test'].insert_rows(2) # get time and date dt = datetime.now() cdate = dt.strftime('%x') ctime = dt.strftime('%X') # put values in row 2 # in this XL column 1 is id an integer starting at 1 # this increments id upwards, row 2 is the highest id, the latest data (if that is the goal) idd = wb['test'].cell(row=3, column=1).value + 1 # not sure how you are getting rowlist but len(rowlist) should probably be = maxCol rowlist = [idd, 'V', 'indifferent', ctime, cdate] for i in range(1, maxCol + 1): wb['test'].cell(row=2, column=i, value=rowlist[i-1]) wb.save(path2XL) print(f'Added a row to {path2XL} at row 2.')