需求
原始表格:
想在Total列中对每日的Amount进行汇总,然后对Date和Total进行合并居中,效果如下:
思路
遍历Excel行,从第一个非空Date列开始,到下个非空Date列,对Amount列进行求和,结果赋给第一个非空Data列对应行的Total列。
代码
import os import openpyxl from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment def range_sum(worksheet,start,end): sum = 0 for row in worksheet[start:end]: for cell in row: if cell.value != None: sum += cell.value return sum def is_blank_row(worksheet,row_num,max_col=None): if not max_col: max_col = worksheet.max_column for cell in worksheet[row_num][:max_col]: if cell.value: return False return True def total_amount(worksheet): """ 对某sheet的A、E列合并居中,并对E列求和 """ ws = worksheet row, max_row = 4, ws.max_row while row < ws.max_row: sum_row_start, sum_row_end = row, row for working_row in range(row + 1,max_row + 2): if (not is_blank_row(worksheet, working_row-1) # 上一行有值 and (ws[f'A{working_row}'].value or is_blank_row(worksheet, working_row))): # A列有值 或 当前为空行(最后一次合并) # 求和 sum_row_end = working_row - 1 ws[f'E{sum_row_start}'] = range_sum(ws,f'C{sum_row_start}',f'C{sum_row_end}') # 合并居中 ws[f'E{sum_row_start}'].alignment = Alignment(horizontal="center", vertical="center") ws[f'A{sum_row_start}'].alignment = Alignment(horizontal="center", vertical="center") ws.merge_cells(f'E{sum_row_start}:E{sum_row_end}') ws.merge_cells(f'A{sum_row_start}:A{sum_row_end}') break row = sum_row_end + 1 def main(): # 根据情况修改代码 in_file_name = 'In.xlsx' processing_sheet = 'Sheet1' path_name = 'D:\\Users\\Desktop\\Temp' out_file_name = 'Out.xlsx' wb = openpyxl.load_workbook(filename=os.path.join(path_name,in_file_name)) total_amount(wb[processing_sheet]) wb.save(os.path.join(path_name,out_file_name)) if __name__=='__main__': main()
说明
本功能用到了openpyxl模块,更多Excel操作请见官网
本代码不支持Excel中间有空行的情况,最后有空行无影响
f'A{sum_row_start}'这样的代码用到了f-string功能,若python版本低于3.6,需改为'A'+str(sum_row_start)或其它形式
补充:Python3 Pandas DataFrame 对某一列求和
在操作pandas的DataFrame的时候,常常会遇到某些列是字符串,某一些列是数值的情况,如果直接使用df_obj.apply(sum)往往会出错
使用如下方式即可对其中某一列进行求和
dataf_test1['diff'].sum() // diff为要求和的列
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。