Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert row + shifting cells in openpyxl

Tags:

openpyxl

I was thinking inserting some cells on specific columns. This is to fix dynamic data between the "Header" and "Total" while getting the format of the cells in between the Header and Total. (see Excel screenshot).

Excel screenshot:

Excel Reference

What I tried

I tried using insert_rows method but it does insert for the entire row/column (correct me if I am wrong here).

Does openpyxl support the insert row method with "shift cells right/down"?

like image 581
jpm Avatar asked Dec 08 '25 08:12

jpm


1 Answers

(Sources:

  • https://openpyxl.readthedocs.io/en/stable/editing_worksheets.html#moving-ranges-of-cells

  • https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/worksheet/worksheet.html#Worksheet.move_range )

I believe the method that you are looking for is openpyxl.worksheet.worksheet.Worksheet.move_range(). This method allows you shift a range of cells within a worksheet. You can specify either the number of rows to move the range, or the number of columns to move the range, or both. Here is the docstring for the method:

    """
    Move a cell range by the number of rows and/or columns:
    down if rows > 0 and up if rows < 0
    right if cols > 0 and left if cols < 0
    Existing cells will be overwritten.
    Formulae and references will not be updated.
    """

CAUTION: WHATEVER CONTENT IS IN THE DESTINATION CELLS WILL BE OVERWRITTEN

I have created an example worksheet that is populated by a 9x9 grid to demonstrate.

from openpyxl import Workbook

wb = Workbook()

dest_filename = 'empty_book.xlsx'

ws1 = wb.active

# create a 9x9 grid of numbers
for row in range(1, 10):
    ws1.append(range(10))

# move some numbers
ws1.move_range("H5:J9", rows=2, cols=3)

# move some numbers down 1 row
ws1.move_range("A3:B9", rows=1)

wb.save(filename = dest_filename)

Voila! The range H5:J9 has moved down 2 rows and right 3 columns, and the range A3:B9 has moved down 1 row. This is the same result was would have been achieved in normal Excel using Insert>Shift cells down and Insert>Shift cells right.

Excel result

like image 138
TookieWookie Avatar answered Dec 12 '25 12:12

TookieWookie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!