#coding=utf-8 import numbers import os import openpyxl from openpyxl import load_workbook from openpyxl.styles import NumberFormatDescriptor path_sum="C:\\Users\\user\\Desktop\\费用统计2023年1-9月" path_units="C:\\Users\\user\\Desktop\\费用统计2023年1-9月\\各单位报送" #遍历文件路径使用os.walk方法 # for i,j,k in os.walk(path_sum): # print(i,j,k) #使用os.listdir获取文件名 # 创建工作路径列表 files=[] for file in os.listdir(path_units): file_path=os.path.join(path_units,file) # print(file_path) files.append(file_path) # print(files) # 创建工作簿列表 wb_units=[] wb_units=[load_workbook(file,data_only=True) for file in files] #查看列表元素个数 n=len(wb_units) print(n) # file_sum='分产品费用明细表-2023年9月-汇总.xlsx' wb_sum=load_workbook('C:\\Users\\user\\Desktop\\费用统计2023年1-9月\\分产品费用明细表-2023年9月-汇总.xlsx') ws_sum=wb_sum.worksheets[1] # # 打印工作表名称 # sheet_names = wb_sum.sheetnames # for sheet_name in sheet_names: # print(sheet_name) # 打开每个工作簿第二张表 # sheet_names = wb[i].sheetnames # for sheet_name in sheet_names: # print(sheet_name) for row_num in range(7,39): for col_num in range(3,49): ws_sum.cell(row_num, col_num).value=0 for i in range(0, len(wb_units)): print(i) ws_units = wb_units[i].worksheets[1] cell_value_units=ws_units.cell(row_num,col_num).value print(cell_value_units) if cell_value_units is not None: if isinstance(cell_value_units,str): try: cell_value_cache=float(cell_value_units) except ValueError: cell_value_cache=0 else: cell_value_cache=cell_value_units else: cell_value_cache = 0 print(cell_value_cache) ws_sum.cell(row_num,col_num).value += cell_value_cache print(ws_sum.cell(row_num,col_num).value) # 输出行列号和值 cell= ws_sum.cell(row_num,col_num) row_number = cell.row column_number = cell.column print(f"Row: {row_number}, Column: {column_number}") # print(ws_sum.cell(row_num,col_num).value) wb_sum.save("C:\\Users\\user\\Desktop\\费用统计2023年1-9月\\分产品费用明细表-2023年9月-汇总-python.xlsx")