1

I started learning python and was trying to work on a small project for myself. Its just to open an excel spreadsheet then look in one column and then randomly choose one of the cells to print. I did some research and found multiple ways to do it but kind of liked this one due to it being short and sweet. The problem I am having is just when it prints i want it to randomize the selection in one column. So wanted to know if there is a way for me to do it. Thanks all help will be appreciated!!!!

import xlrd

wb = xlrd.open_workbook("quotes.xlsx")
sh1 = wb.sheet_by_index(0)

print sh1.cell(0,0).value
shengy
  • 9,461
  • 4
  • 37
  • 61

1 Answers1

1

Use the following:

from random import choice
import xlrd

wb = xlrd.open_workbook("quotes.xlsx")
sh1 = wb.sheet_by_index(0)
column = 2 # or whatever column you want to select from

print choice(sh1.col(column)).value

The Sheet.col() method returns a list, and random.choice returns a random element from a list.

If you want to restrict the rows from which you randomly select an element you can generate a random row number and use that to index the column instead. You can do that like this:

import random

startRow = 3
endRow = 29
row = random.randint(startRow, endRow)
print sh1.cell(column, row).value

See also: How to randomly select an item from a list?

Community
  • 1
  • 1
chandsie
  • 2,865
  • 3
  • 27
  • 37
  • That helped! But how do I have it stop at a certain row? The column does not change but have different cells filled with data in that one column. Need it to randomize selection of the cells in that one column – user3171480 Jan 08 '14 at 02:59
  • I'm sorry but I don't quite understand what you're trying to get at. Do you want to restrict the number of rows you're looking at? Or do you want to randomize the column selection as well? – chandsie Jan 08 '14 at 03:04
  • Restrict the number of rows that it looks at in one column. Hopefully that makes sense. – user3171480 Jan 08 '14 at 03:09
  • Tried it but got IndexError: array index out of range...I think I am doing something wrong...Just a beginner so bear with me please. File "/usr/local/lib/python2.7/dist-packages/xlrd/sheet.py", line 399, in cell self._cell_types[rowx][colx], – user3171480 Jan 08 '14 at 03:31
  • You should check to make sure that the cell you are trying to look up actually exists. Keep in mind that `randint(a, b)` returns a random integer between `a` and `b` *inclusive*. – chandsie Jan 08 '14 at 05:18
  • 1
    Got it to work eventually. Should of mentioned something earlier. You were really helpful and I appreciate that alot. Thanks for all of your help. – user3171480 Jan 08 '14 at 05:29