简体   繁体   中英

How to randomly select an Excel cell from a column?

I'm trying to randomly select an individual cell from a column of an Excel worksheet in Tkinter. I have tried a few different ways:

1st, I tried:

wb = load_workbook('Test_Workbook.xlsx')
ws = wb.active

range = ws['A2':'A7']

for cell in range:
    for x in cell:
        print(random.choices((x.value)))

2nd, I tried

wb = load_workbook('Test_Workbook.xlsx')
ws = wb.active

A = ws['A']
print(A)
for cell in A:
    print(random.choices(f'{cell.value}') )

Both examples output random letters of a string inside the cells instead of picking a random cell from the column. How would I get it to return the value of a random individual cell?

There are multiple ways to achive this and I try to stick close to your appoaches. So the first thing to see is, that to call a cell in the worksheet object, you do so using the A1 notation eg ws["B5"] . If the range you want to select from now is A2:A7 you would need a list such as

l = ['A1','A2',..'A7']
rand_cell = random.choice(l)

Now to automate this a little, you can do something like the following:

column = 'A'
row_range = list(range(2,8)) # [1,2,...7]

and select a random value from row_range and concatenate the two

rand_cell = "{column}{row}".format(column = column, row = random.choice(row_range))

Full example:

wb = load_workbook('Test_Workbook.xlsx')
ws = wb.active

column = 'A'
row_range = list(range(2,8)) # [1,2,...7]

rand_cell = "{column}{row}".format(column = column, row = random.choice(row_range))

print(ws[rand_cell])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM