我需要计算 H 列中值的总和。我使用 xlwings python 在 E 列中应用了自动过滤器。
我试过这个:
first_row_sheet1 = ws.range('B1').row
print(first_row_sheet1)
lastrow_sheet1 = ws.range('B1').end('down').row
print(lastrow_sheet1)
for x in range(first_row_sheet1, lastrow_sheet1+1):
column_B = ws1.api.Range("H"+str(x)).Value
print(column_B)
此示例假设您的工作表应用了过滤器,并且您想在 Python 中计算总和(即不在工作表中插入公式)。
过滤将不需要的行更改为
hidden
,从而保留所需的显示。因此,要计算所需列中显示的单元格的值,您只需循环范围并仅在计算中包括未隐藏行中的那些单元格。worksheet.used_data
行确定,这是第一行“已使用的单元格”和 last_row
计算。对于过滤后的数据,last_row
将在未过滤时返回最后一个可见行的行号。ws.range('H3:HX')
,其中 X 是满足指示的筛选标准的最后一行。import xlwings as xw
file = 'foo.xlsx' # Workbook
filtered_sheet = 'Sheet1' # Sheet with filtered data
calc_column = 'H' # Column to SUM
with xw.App() as app:
wb = xw.Book(file)
ws = wb.sheets[filtered_sheet]
### Row to start calculation from. One after the 1st row in used_range to skip the Header Row
start_row = ws.used_range.row + 1
### Max rows in the filtered range
last_row = ws.range(calc_column + str(wb.sheets[0].cells.last_cell.row)).end('up').row
column_sum = 0 # variable to hold calculated value
### Loop over range in calc_column from start_row to last row in filtered data
for cell in ws.range(f'{calc_column}{start_row}:{calc_column}{last_row}'):
if not cell.api.EntireRow.Hidden: # Select cell if row is not hidden
column_sum += cell.value # Sum value in the cell to total
### Print calculated value
print(f'SUM Cells = {column_sum}')
使用示例屏幕截图,这将导致计算值
30