Python Forum
openpyxl issue - How to reset sheet.ins_row to the real last row ...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
openpyxl issue - How to reset sheet.ins_row to the real last row ...
#3
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.

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.')
Reply


Messages In This Thread
RE: openpyxl issue - How to reset sheet.ins_row to the real last row ... - by Pedroski55 - Nov-08-2023, 08:15 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  openpyxl rename sheet acting strange Pedroski55 1 2,093 Sep-26-2022, 08:56 AM
Last Post: buran
  Append excel sheet using openpyxl TammyP 1 2,522 Feb-02-2021, 06:32 PM
Last Post: nilamo
  Excel: Apply formating of a sheet(file1) to another sheet(file2) lowermoon 1 2,129 May-26-2020, 07:57 AM
Last Post: buran
  Openpyxl - When save existing xlsx sheet, images/drawing does not get saved shubhamjainj 2 8,683 Apr-16-2019, 07:09 AM
Last Post: shubhamjainj
  inserting photos in 1 sheet of a 6 sheet excel file fails Pedroski55 0 2,436 Mar-03-2018, 01:53 AM
Last Post: Pedroski55
  openpyxl saving files issue Pedroski55 1 6,805 Sep-16-2017, 02:05 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020