Python:如何从一个 XLSX 文件中搜索字符串以在另一个 XLSX 文件中出现?

Python: How do I search a string from one XLSX to be in another XLSX file?

我有两个 XLSX 文件(Cookie 和 Cream),我想知道 A 列(Cookie 中)每一行的值是否存在于 D 列(Cream 中)的某行中。

使用openpyxl,我导出了如下代码:

for mrow in range(1, Cookies.get_highest_row() +1):
    for arow in range(1, Cream.get_highest_row() +1):
        if cookies['A' + str(mrow)].value == cream['D' + str(arow)].value:
               print(cookies['A' + str(mrow)].value)
               break

尽管这确实按预期工作,但这需要很长时间才能执行,因为 cookie 包含大约 7000 行,而 cream 有超过 24,000 行。

感谢您的帮助

这是我的工作,但请注意,这没有使用 openpyxl 包的任何特殊方法(正在处理)。但是,它应该足以加快您的工作速度。该算法总体上更快,并且避免了openpyxl中的一些陷阱(所有单元格的内存分配,请参阅关于中途的警告:http://openpyxl.readthedocs.org/en/latest/tutorial.html

def findAinD(cookies, cream):  # assumes that cookies and cream can be treated as such in the for loop will fail otherwise
    A1 = []
    D1 = []

    for mrow in range(1, Cookies.get_highest_row() + 1):
        A1 += cookies['A' + str(mrow)]
        D1 += cream['D' + str(mrow)]

    A1.sort()  # Alphabetical
    D1.sort()  # ^


    for i, cookie in enumerate(A1): # Enumerate returns the index and the object for each iteration
        A1[i] = D1.index(cookie)    # If cookie IS in D, then A1[i] now contains the index of the first occurence of A[i] in D
                                    # If cookie is not, then the result is -1, which is never an index,
                                    #  and we filter those out before round 2 (not shown)

    return A1

使用此方法,通过检查负数、过滤等方式分析返回的对象

openpyxl 确实允许您直接访问列,但您仍然需要自己检查单元格。您的代码将是这样的:

cookies = load_workbook("cookies.xlsx")
cream = load_workbook("cream.xlsx")
ws1 = cookies['sheetname']
ws2 = cream['sheetname2']

cookies_a = ws1.columns[0]
cream_d = ws1.columns[4]

for c1, c2 in zip(cookies_a, cream_d):
    if c1.value == c2.value:
         break

如果您有非常大的文件,这会很慢。可以使用解析代码在字符串和使用它们的单元格之间创建参考图,但您最好使用 xlwings 之类的东西来自动化 Excel 并让它完成工作。