[英]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.在我的 Excel 电子表格中,我需要在底部输入 excel 公式来汇总值。 Number of rows can be different.行数可以不同。 But not columns.但不是专栏。
So in cell B10 should be =SUM(B2:B7)
所以在单元格 B10 中应该是=SUM(B2:B7)
in cell C10 should be =SUM(C2:C7)
在单元格 C10 中应该是=SUM(C2:C7)
in cell D10 should be =SUM(D2:D7)
在单元格 D10 中应该是=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你可以在哪里做
... ...
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.我认为唯一的问题是公式本身:如何自动生成'=SUM(A2:A10)'
然后'=SUM(B2:B10)'
。 What you are looking for are the functions ord()
and chr()
:您正在寻找的是功能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})')
You may want to wrap after 26 characters to get this 'Z', 'AA' behavior in the names if you have large numbers.如果数字很大,您可能希望在 26 个字符后换行以获得名称中的“Z”、“AA”行为。 See this answer how you can iterate over a list of wrapping characters.请参阅此答案,了解如何迭代换行符列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.