【问题标题】:How to read excel files in a for loop with openpyxl?如何使用openpyxl在for循环中读取excel文件?
【发布时间】:2016-04-16 02:44:08
【问题描述】:

这对我来说似乎很棘手。假设我有一个嵌套在目录树中的 excel 文件,其中包含一些非空列。我想用openpyxl 获得位于 F 列中的所有值的总和:

file1.xlsx
A  B  C  D  E  F
               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。如何解决这个问题?

【问题讨论】:

  • 您没有在任何地方定义“细胞”。你的意思是在“for row in cell_range:”下再添加一个for循环,比如,'for cell in row:'?

标签: python excel for-loop openpyxl


【解决方案1】:

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

在代码的末尾,您可以这样做(替换代码的两端):

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 文件中运行。这本来很容易调试。删除之后的所有代码

ws=wb.active

并添加

print(name + ' : ' + ws)

这将打印出所有的 excel 文件名及其活动工作表。如果它打印出超过1,那么它显然是在爬过并抓取excel文件......

【讨论】:

    猜你喜欢
    • 2022-06-23
    • 1970-01-01
    • 2015-09-04
    • 2011-12-04
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多