I am having a lot of success using openxpyxl to do many operations. I have a table of dates, numbers and formulas that I insert a new row within the table and enter some easy data (date, name, amount) but I am having trouble with columns that have simple formulas like cell F7 would be ‘=F6+C7’. F8 would be ‘=F7+C8’ etc down the table. When I insert the new (empty) row in the middle of the table, the rows below the insertrow do not get updated with the correct indexed. For example F24 becomes ‘=F22+C23’ instead of incrementing to ‘=F23+C24’ like it would do if I used an excel ‘fill down’ in the spreadsheet. So I am looking for help getting this to work. I have tried many things shown here:
The basic for statement is:
for row in range(8, finalrow + 1):
cell_value = f"=F{row-1} + C{row}"
print("cell formula", cell_value)
I have tried each of these things:
-
worksheet2.cell(row=row, column=6,value=form_data[‘cell_value’]).font=red_font
-
worksheet2.array_formulae[“F{row}”] = “=F{row-1} + C{row}”
-
worksheet2.cell(row=row, column=6, value=”=F{row-1} + C{row}”).font = red_font
-
worksheet2.cell(row=row, column=6, value=form_data[f”=F{row-1} + C{row}”]).font = red_font
-
worksheet2[f”C{row}”] = Translator(“=B6/$F$3)”, origin=”c7″).translate_formula(f”C{row}”)
Comment on 5) – I believe Translator is the command I want to use but I cannot understand how to use it in this case as a fill down. For this Translator line I received this error message File “C:C Drive DocumentsPete HomePython Excelbond-input.py”, line 292, in
worksheet2[f”F{row}”] = Translator(“=C8+F7)”, origin=”F7″).translate_formula(f”F{row}”)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:UserslarocAppDataLocalProgramsPythonPython312Libsite-packagesopenpyxlformulatranslate.py”, line 50, in init
self.tokenizer = Tokenizer(formula)
^^^^^^^^^^^^^^^^^^
File “C:UserslarocAppDataLocalProgramsPythonPython312Libsite-packagesopenpyxlformulatokenizer.py”, line 53, in init
self._parse()
File “C:UserslarocAppDataLocalProgramsPythonPython312Libsite-packagesopenpyxlformulatokenizer.py”, line 87, in _parse
self.offset += dispatchercurr_char
^^^^^^^^^^^^^^^^^^^^^^^
File “C:UserslarocAppDataLocalProgramsPythonPython312Libsite-packagesopenpyxlformulatokenizer.py”, line 246, in _parse_closer
token = self.token_stack.pop().get_closer()
^^^^^^^^^^^^^^^^^^^^^^
IndexError: pop from empty list -
I saw this solution using xlswrite package – but xlswriter cannot open up an existing .xlsx file to edit so I cannot use it.
worksheet2.write_formula(f”f{row}”, ‘cell_value’) # from xlxwriter
So any creative solution doing a ‘select’ and ‘fill down’ using openpyxl I would appreciate or any syntax corrections in my attempts would be useful.
BTW – I had no idea how to start with this so I had ChatGPT generate the code which is how I got started and that solution did not work.