简体   繁体   中英

How to write excel formula (SUM()) dynamically in a range of columns using openpyxl?

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?

You can do this where

  1. first_row is the start of the summing rows
  2. sum_row is the row where the totals will be placed. Here its 3 rows down from last_row
  3. start_col is the first column to add the SUM formula ie col B
  4. end_col is the last column to add the SUM formula ie 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM