Hello to all! An interesting question was asked to me on Telegram a few days ago. In general, it came down to a task that sounded like: search in an Excel file. Let’s try to solve it? 🙂

Actually, any Excel file is a certain number of rows and columns. We work, as always – using the Openpyxl library, and to work with each individual cell, we use the while loop.

In general, the algorithm of the code comes down to:

1. Open the file ( I wrote about this earlier )

2. Read the first cell in the row

3. Go to the next row in this column.

4. After you have reached the maximum in the number of cells in the column, go to the next column.

5. And so on until the file is completely processed.

** Important **: in order for the cycle to work, we need to know the number of cells in rows and columns. To do this, use the constructs in the form:

row_max = sheet_active.max_row # Get the number of columns

and:

column_max = sheet_active.max_column # Get the number of columns

The code itself with comments is available below.

import openpyxl

from openpyxl.utils import get_column_letter

import re

path_to_file = 'base_to_search.xlsx'

search_text = input(str('What text are we looking for: '))

search_text = search_text.lower()

print('Ищем:', search_text)

wb = openpyxl.load_workbook(path_to_file) #Loaded our price list

sheets_list = wb.sheetnames # Get a list of all sheets in a file

sheet_active = wb[sheets_list[0]] # Getting started with the very first

row_max = sheet_active.max_row # Get the number of columns

#print(type(row_max))

column_max = sheet_active.max_column #Get the number of rows

print('In file:', path_to_file, '\n Columns:', row_max, '\n rows:', column_max)

row_min = 1 #Variable for line number

column_min = 1 #Column Number Variable

while column_min <= column_max:

row_min_min = row_min

row_max_max = row_max

while row_min_min <= row_max_max:

row_min_min = str(row_min_min)

word_column = get_column_letter(column_min)

word_column = str(word_column)

word_cell = word_column + row_min_min

data_from_cell = sheet_active[word_cell].value

data_from_cell = str(data_from_cell)

#print(data_from_cell)

regular = search_text

result = re.findall(regular, data_from_cell)

if len(result) > 0:

print('Нашли в ячейке:', word_cell)

row_min_min = int(row_min_min)

row_min_min = row_min_min + 1

column_min = column_min + 1

Of course, I will be glad to any comments and questions. To do this, use mail or Telegram.

### Like this:

Like Loading...

*Похожее*