Python 對Excel求和、合並居中的操作

需求

原始表格:

想在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為要求和的列

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: