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.

1
  • 1
    Perhaps this thread is of help to you: stackoverflow.com/questions/16888888/… Read the Exel file properly and iterate over its cells to check for abc. Commented Oct 22, 2019 at 0:11

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sen, this worked perfectly fine! Also, thanks to all of you who suggested some answers, they were very much appreciated.
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")

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.