簡體   English   中英

如何使用openpyxl在for循環中讀取Excel文件?

[英]How to read excel files in a for loop with openpyxl?

這對我來說似乎很棘手。 假設我有一個嵌套在目錄樹中的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: # 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文件...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM