-1

I've been referring many articles and tried many code snippet, but not able to achieve. openpyxl package insert_rows is not working.

import openpyxl

wb = openpyxl.load_workbook('sample.xlsx')
sheet = wb['Sheet1']

sheet.insert_rows(idx=1, amount=3)
sbkhbk
  • 31
  • 2
  • 8

1 Answers1

1

It should work, It will "Insert row or rows before row==idx" Try this:

import openpyxl
wb = openpyxl.load_workbook('sample.xlsx')
sheet = wb['Sheet1']
sheet['A1']=10
sheet.insert_rows(idx=0, amount=3)
wb.save('sample.xlsx')

Now the value 10 will move to D1.

codebee
  • 824
  • 1
  • 9
  • 22
  • Cool, infact i just made a slight mistake i kept the excel file open while i was trying to manipulate it. My bad. – sbkhbk Oct 12 '19 at 10:17
  • However, another question is that, I’ve formatted my sheet, so when am inserting a new row it inserts new row without formatting . If i do inserting in excel directly the format is retained while you insert inbetween. Is there any option like that in openpyxl? To insert rows by copying the formatting of previous row lets say. – sbkhbk Oct 12 '19 at 10:19
  • Yes check this out: https://stackoverflow.com/questions/23332259/copy-cell-style-openpyxl/34838233 – codebee Oct 14 '19 at 17:34