Vvega
Vvega

Reputation: 37

Read and output specific cells in a column by row number using openpyxl

The code posted was compiled from researching other sources with similar projects.

The following code gives the row number of a cell value - in this case "asset" that I am looking up in column D.

I was wondering if it is possible to then use rownum to read specific cells in that row number ? - i.e cell values in columns E, and Q

print("loading database..")

from openpyxl import load_workbook
wb = load_workbook(filename = 'itimsdb.xlsx')
ws = wb['Sheet1']
sheet_ranges = wb['Sheet1']

userInput = input("Scan asset now:")
strValue=userInput

for row in range(ws.max_row):
    for column in "D":
        cell_name = "{}{}".format(column, row+1)
        value= str(ws[cell_name].value)
        if value==strValue:
            rownum = row

            # to verify row number
            print(rownum+1)

New version:

I went with .CSV db instead. Now I have to figure out how to loop it and resume scanning and writing out new lines for different assets.

import csv


userInput = input("Scan asset now:")
strValue=userInput

with open('mydb.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        for field in row:
            if field == strValue:


                with open('test.csv', "w") as csv_file:
                    writer = csv.writer(csv_file, delimiter=',')
                    for row in reader:
                        writer.writerow(row)
                        print(row)
                        break

Upvotes: 0

Views: 1896

Answers (1)

Charlie Clark
Charlie Clark

Reputation: 19507

Always use ws.iter_rows() or ws.iter_cols() instead of constructing your own range. For ad hoc access you can also use ws[E] and ws[E:Q] or ws[4] and ws[4:6] so that you never need to create Excel-style coordinates.

Upvotes: 1

Related Questions