In my Excel spreadsheet I need to enter excel formula on a bottom that will summarize values. Number of rows can be different. But not columns.
So in cell B10 should be =SUM(B2:B7)
in cell C10 should be =SUM(C2:C7)
in cell D10 should be =SUM(D2:D7)
and so on...
import openpyxl
wb = openpyxl.load_workbook("C:\\Users\\my\\Test.xlsx")
# open sheet to write into.
ws = wb.active
#Get the number of rows to make it easier to add our Excel formulas a little later
last_row = ws.max_row
for col in ws.iter_cols(min_row=last_row 2, min_col=14, max_row=last_row 2, max_col=28):
for cell in col:
cell.value = '=SUM(A2:B2)' # hou to make formula dynamic?
CodePudding user response:
The code looks good. I assume that the only problem is the formula itself: how to make '=SUM(A2:A10)'
and then '=SUM(B2:B10)'
automatically.
What you are looking for are the functions ord()
and chr()
:
last_row = 42
for i in range(26):
current_col_num = ord('A') i
current_col = chr(current_col_num)
print(f'=SUM({current_col}2:{current_col}{last_row})')
You may want to wrap after 26 characters to get this 'Z', 'AA' behavior in the names if you have large numbers. See this answer how you can iterate over a list of wrapping characters.
CodePudding user response:
You can do this where
- first_row is the start of the summing rows
- sum_row is the row where the totals will be placed. Here its 3 rows down from last_row
- start_col is the first column to add the SUM formula i.e. col B
- end_col is the last column to add the SUM formula i.e. col M
...
first_row = 2
last_row = ws.max_row
sum_row = last_row 3
start_col = 2
end_col = 13
for row in ws.iter_rows(min_row=sum_row, max_row=sum_row, min_col=start_col, max_col=end_col):
for cell in row:
cell_sum_start = cell.column_letter str(first_row)
cell_sum_end = cell.column_letter str(last_row)
cell.value = '=SUM({0}:{1})'.format(cell_sum_start, cell_sum_end)