如何在openpyxl for循环中读取excel文件?

这对我来说似乎很棘手。 比方说,我已经嵌套在一个目录树中,有一些非空列的excel文件。 我想用openpyxl得到F列中所有值的总和:

 file1.xlsx ABCDEF 5 7 11 17 20 29 34 

我认为这将是如下,但它是错误的:

 import os from openpyxl import load_workbook directoryPath=r'C:\Users\MyName\Desktop\MyFolder' #The main folder os.chdir(directoryPath) folder_list=os.listdir(directoryPath) for folders, sub_folders, file in os.walk(directoryPath): #Traversing the sub folders for name in file: if name.endswith(".xlsx"): filename = os.path.join(folders, name) wb=load_workbook(filename, data_only=True) ws=wb.active cell_range = ws['F1':'F7'] #Selecting the slice of interest sumup=0 for row in cell_range: sumup=sumup+cell.value 

当运行这个我得到的NameError: name 'cell' is not defined 。 如何解决这个问题?

目前错误的主要是你只遍历行,而不是行内的列(单元格)。

在代码结束时,可以这样做(replace代码的两个最后一行):

 for row in cell_range: # This is iterating through rows 1-7 for cell in row: # This iterates through the columns(cells) in that row value = cell.value sumup += value 

你确定你不认为这是通过你的每个Excel文件。 这将是非常容易debugging。 删除所有代码后

 ws=wb.active 

并添加

 print(name + ' : ' + ws) 

这将打印出所有的Excel文件名称,以及他们的活动工作表。 如果它打印出来超过1,那么它显然是抓取并抓取excel文件…