簡體   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