主要功能就是把F列三行合并居中
python3 自动编辑excel的脚本-LMLPHP


点击(此处)折叠或打开

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Time : 2020/3/5 19:49
  4. # Author : xuekai
  5. # Email : xuekai20080901@aliyun.com
  6. # File : excel.py
  7. # Project : python
  8. import os
  9. import openpyxl
  10. from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment


  11. # 函数:范围单元格求和
  12. def range_sum(worksheet, start, end):
  13.     sum = 0
  14.     for row in worksheet[start:end]:
  15.         for cell in row:
  16.             if cell.value != None:
  17.                 sum += cell.value
  18.     return sum


  19. # 函数:对某sheet求和并居中
  20. def total_amount(worksheet):
  21.     ws = worksheet
  22.     row, max_row = 2, ws.max_row
  23.     print("row:%s max_row:%s ws.max_row:%s" %(row,max_row,ws.max_row))
  24.     while row < ws.max_row:
  25.         sum_row_start, sum_row_end = row, row
  26.         for working_row in range(row + 1, max_row):
  27.             # 长条件,换行增强可读性
  28.             if (ws['A' + str(working_row)].value != None
  29.                     or (ws['C' + str(working_row)].value == None
  30.                         and ws['C' + str(working_row - 1)].value != None)):
  31.                 sum_row_end = working_row - 1
  32.                 #print(sum_row_end)
  33.                 # 求和
  34.                 ws['D' + str(sum_row_start)] = range_sum(ws, 'C' + str(sum_row_start), 'C' + str(sum_row_end))
  35.                 # 合并
  36.                 ws.merge_cells('D' + str(sum_row_start) + ':D' + str(sum_row_end))
  37.                 ws.merge_cells('A' + str(sum_row_start) + ':A' + str(sum_row_end))
  38.                 # 居中
  39.                 ws['D' + str(sum_row_start)].alignment = Alignment(horizontal="center", vertical="center")
  40.                 ws['A' + str(sum_row_start)].alignment = Alignment(horizontal="center", vertical="center")

  41.                 break;
  42.         row = sum_row_end + 1;


  43. # 根据情况修改代码
  44. os.chdir('D:\\')
  45. wb = openpyxl.load_workbook('in.xlsx')

  46. total_amount(wb['Sheet1'])
  47. wb.save('Out.xlsx')


操作完成之后的样子,
python3 自动编辑excel的脚本-LMLPHP


09-27 07:54