如何从大量excel文件中找到特定值?

2024-06-17 16:17:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从一个文件夹中的一大堆excel文件(大约800个文件)中找到一个excel文件(比如“543.45”)的特定值。我该怎么做


Tags: 文件文件夹excel
1条回答
网友
1楼 · 发布于 2024-06-17 16:17:11

您可以使用xlrd模块处理Excel文件。我以前从未使用过xlrd,但我花了半个小时的时间来理解这段代码:

import xlrd
import os
import time
directory = input("Enter the folder with Excel files: ")
number = input("What number would you like to find? ")
number = float(number)
os.chdir(directory)
for filename in os.listdir(directory): # Iterates through each file
    if filename.endswith(".xlsx") or filename.endswith("xlsm"):
        book = xlrd.open_workbook(filename)
        sheet = book.sheet_by_index(0)
        for row in range(sheet.nrows): # Iterates through each row
            for column in range(sheet.ncols): # Iterates through each column
                currentcell = sheet.cell_value(row, column) # Gets the value for the row and column it is currently on
                try:
                    currentcell = float(currentcell)
                except ValueError: # In case the cell contains a string.
                    pass
                if currentcell == number:
                    print("Found the value {} in the file {} at {}:{} (col:row)".format(number, filename, column, row))

请注意,您必须关闭任何试图检查的excel文件

它遍历每个文件、每一行和每一列,以检查数字是否等于指定的数字,因此虽然有效,但效率不高。它将返回在哪个文件中找到号码的位置

我使用的链接:

相关问题 更多 >