0

I am trying to make python find a specific word in an excel sheet. Nonetheless, despite searching literally everywhere how to do this, I can't find an answer.

import re

with open('ptry.xlsx') as aa:
    for line in aa:
        match = re.search(r'abc', line)
        if match:
            print("yes")
        else:
            print ("no")

This code gives me the following result:

no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no

Repl Closed

Nonetheless, I am expecting a simple "yes" as the word "abc" is on my excel sheet.

pppery
  • 3,434
  • 13
  • 24
  • 37
Fcas
  • 1
  • 1
    Perhaps this thread is of help to you: https://stackoverflow.com/questions/16888888/how-to-read-a-xlsx-file-using-the-pandas-library-in-ipython Read the Exel file properly and iterate over its cells to check for `abc`. – Jens Oct 22 '19 at 00:11

3 Answers3

1

If you are using Excel, can I suggest using Openpyxl?

import os
#Change to the dir of your spreadsheet

from openpyxl import load_workbook

wb = load_workbook(filename='Insert your file here', data_only=True)
#data_only=False by default
#If you want to see data instead of formulas, set data_only=True

ws = wb['Sheet1'] #Or whatever your sheet name is

for num_row in range (1, ws.max_row):
    if ws['A{}'.format(num_row)].value=='abc':
        print ('yes')
    else:
        print ('no')
#You can also use ws.max_column

This should give you a general idea of using openpyxl. Let me know if you have any other questions.

Sen
  • 90
  • 8
  • Thank you Sen, this worked perfectly fine! Also, thanks to all of you who suggested some answers, they were very much appreciated. – Fcas Oct 22 '19 at 02:31
1

There may be a better way, but this one does the trick. In the code below a copy of the excel file is created in a text format and then a list is created and checked for the "word" in the file.

import pandas as pd

df = pd.read_excel("ptry.xlsx")
df.to_csv("ptry.txt")

filex = open("ptry.txt", "r")
filex_string = filex.read()
filex_list = filex_string.split(",")

if "word" in filex_list:
    print("True")
else:
    print("false")
JJSSEE
  • 34
  • 6
0
import openpyxl

excel_var = openpyxl.load_workbook('excelname.xlsx')

sheet = excel_name.get_sheet_by_name('sheetname')

for row in sheet.iter_rows(min_row=minr, min_col=5, max_col=11, max_row=maxr):
    match = re.search(r'abc', line)
    if match:
        print("yes")
    else:
        print("no")

Take a note you should limit the rows and cols in the for loop there is a vars minr and maxr