|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
- import xlwings as xw
- # 打开excel程序, visible 是否可见, add_book 是否添加新工作簿
- app = xw.App(visible=False, add_book=False)
- # 关闭excel程序的警告
- app.display_alerts = False
- # 关闭屏幕刷新 提高运行速度
- app.screen_updating = False
- try:
- # 打开工作簿
- wb = app.books.open('./project_2/data_original.xlsx', update_links=False)
- # 选定工作表
- sh = wb.sheets['sheet1']
- # 确定需要查找的颜色
- color = (255, 255, 0)
- # sum_path(开始的单元格,结束的单元格,路径) 路径会用((row,column),(row,column),...) 的形式存在
- def sum_path(start,end,path=[]):
-
- row, column = start.row, start.column
- current = start
-
- # 判断是否到达最后一个单元格
- if current.value == end.value:
- # 将路径转化成单元格值
- values = []
- for r, c in path:
- values.append(sh.cells(r,c).value)
- # 将值中整数或浮点求和
- sum = 0
- for i in values:
- if isinstance(i, (int,float)):
- sum += i
-
- print(sum)
- # 确定单元格不是过来的路径
- elif (row,column) in path:
- return
- else:
- path.append((row,column))
- print(path)
- # 左
- if column > 1:
- left = current.offset(column_offset=-1)
- if left.color == color:
- sum_path(left, end, path.copy())
- # 右
- if column < 100:
- right = current.offset(column_offset=1)
- if right.color == color:
- sum_path(right, end, path.copy())
- # 上
- if current.row > 1:
- up = current.offset(row_offset=-1)
- if up.color == color:
- sum_path(up, end, path.copy())
- # 下
- if current.row < 100:
- down = current.offset(row_offset=1)
- if down.color == color:
- sum_path(down, end, path.copy())
- ### 输入起始和重点单元格
- sum_path(sh['A6'],sh['B3'])
- finally:
- # 关闭工作簿
- wb.close()
- # 退出程序
- app.quit()
复制代码
|
|