在Excel文件中按特定字词筛选行

我一直在努力devise一个在Excel文件中search“N”字的python代码。 在任何'N'字的地方,Python代码应该输出这些单词存在的整个行。 我正在寻找一个excel文件中的多个词出现。

假设这种types的Excel文件(称为File.xlsx ):

 ID Date Time Comment 123 12/23/2017 11:10:02 Trouble with pin 98y 01/17/2016 12:45:01 Great web experience. But I had some issues. 76H 05/39/2017 09:55:59 Could not log into the portal. 

根据以上数据,问题是:
如果我要search单词“pin”和“log”并在上面的excel文件中find它,我想让我的python代码输出line1及其下面的输出line3。

从概念上讲,我可以想办法解决这个问题,但Python的实施困扰我。 此外,我已经广泛search堆栈溢出,但找不到解决这个问题的post。

任何和所有的帮助深表谢意。

有很多方法可以完成这个任务,因为有许多Python包可以读取Excel文件( http://www.python-excel.org/ ),但是xlrd可能是最直接的方法:

 import xlrd # package to read Excel file book = xlrd.open_workbook("File.xls") # open the file sh = book.sheet_by_index(0) # get first Excel sheet words = ['pin', 'log'] # list of words to search for rx in xrange(sh.nrows): # for each row in file for word in words: # for each word in list if word in str(sh.row(rx)): # check of word in row print 'line',rx # if so, print row number 

输出:

 line 1 line 3 

这是一个使用openpyxl模块的解决scheme,我已经成功地用于许多项目。

行索引从一个包含头文件开始,因此,如果您不想计算头文件,我们需要将索引计数减less1 row - 1

 from openpyxl import load_workbook wb = load_workbook(filename = 'afile.xlsx') ws = wb.active search_words = ['pin' , 'log'] for row in xrange(1,ws.max_row + 1): for col in xrange(1,ws.max_column + 1): _cell = ws.cell(row=row, column=col) if any(word in str(_cell.value) for word in search_words): print "line {}".format(row - 1) break >>> line 1 line 3 

如果你想输出实际的行,那么只需添加下面的print_row函数

 def print_row(row): line = '' for col in xrange(1,ws.max_column + 1): _cell = ws.cell(row=row, column=col).value if _cell: line += ' ' + str(_cell) return line 

并用print print_row(row)replaceprint "line {}".format(row - 1) print print_row(row)

 >>> 123 2017-12-23 00:00:00 11:10:02 Trouble with pin 76H 05/39/2017 09:55:59 Could not log into the portal. >>>