Python:如何从一个XLSXsearchstring到另一个XLSX文件?

我有两个XLSX文件(cookies和奶油),我想知道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行,而奶油已经超过24000。

谢谢你的帮助

下面是我所做的,但是请注意,这并不使用openpyxl软件包的任何特殊方法。 但是,应该加快你的工作速度。 algorithm总体上更快(不再有n ^ 2废话…),并避免了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 

如果你有非常大的文件,这将是缓慢的。 可以使用parsing代码在string和使用它们的单元格之间创build一个参考graphics,但使用xlwings之类的东西来自动执行Excel并使其工作起来可能会更好。