Python:如何从一个XLSX中搜索一个字符串到另一个XLSX文件中?

2024-06-16 12:59:59 发布

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

我有两个XLSX文件(Cookies和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

尽管这确实如预期的那样工作,但这需要很长时间才能执行,因为cookies包含大约7000行,cream有24000多行。在

谢谢你的帮助


Tags: inforgetvaluerangexlsxrowcookies
2条回答

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并使其完成工作。在

下面是我的解决方案,但请注意,这并没有使用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

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

相关问题 更多 >