繁体   English   中英

如何使用 openpyxl 在一系列列中动态编写 excel 公式(SUM())?

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

在我的 Excel 电子表格中,我需要在底部输入 excel 公式来汇总值。 行数可以不同。 但不是专栏。

所以在单元格 B10 中应该是=SUM(B2:B7)

在单元格 C10 中应该是=SUM(C2:C7)

在单元格 D10 中应该是=SUM(D2:D7)

等等...

在此处输入图像描述

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?

你可以在哪里做

  1. first_row 是求和行的开始
  2. sum_row 是将放置总计的行。 这是从 last_row 向下的 3 行
  3. start_col 是添加 SUM 公式的第一列,即 col B
  4. end_col 是添加 SUM 公式的最后一列,即 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)

代码看起来不错。 我认为唯一的问题是公式本身:如何自动生成'=SUM(A2:A10)'然后'=SUM(B2:B10)' 您正在寻找的是功能ord()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})')

如果数字很大,您可能希望在 26 个字符后换行以获得名称中的“Z”、“AA”行为。 请参阅此答案,了解如何迭代换行符列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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