user330860
user330860

Reputation:

Python xlrd : how to convert an extracted value?

Well i have a question that i feel i've been answered several times, from what i found here. However, as a newbie, i can't really understand how to perform a really basic operation.

Here's the thing :

If anyone can indicate me what i should to only extract the value, formatted as i want, thank you.

Upvotes: 9

Views: 29816

Answers (4)

user7580819
user7580819

Reputation:

This will give you the value of the contents of a cell in Excel.

    var = sh.cell(x,y)
    print var.value

But the type of this data is still 'unicode'. To convert into a string (ascii):

    var.value.encode('ascii','ignore')

Upvotes: 1

evinoshea
evinoshea

Reputation: 42

The correct answer to this is to simply use the Cell.value function. This will return a number or a Unicode string depending on what the cell contains.

Upvotes: 0

Grant Ingram
Grant Ingram

Reputation: 31

You can also just extract values using xlrd rather than getting the full Excel cell returned:

book = xlrd.open_workbook('example.xls')
first_sheet = book.sheet_by_index(0)
print first_sheet.row_values(0)

Gets you the values of the first row in the first sheet.

You can use slices with the row_values (and similarly for columns). So to get values from an entire sheet:

cells = []
for i in range(first_sheet.nrows):
    cells.append(first_sheet.row_values(rowx=i,start_colx=0,end_colx=None))

There may be more elegant ways of using xlrd - but that worked for me.

Upvotes: 3

comamitc
comamitc

Reputation: 841

sh.cell(x, y) returns an instance of the class Cell. When you print sh.cell(x,y) you are returning the repr function of the class (so it prints type:value).

you should try:

cell = sh.cell(x,y)
print(cell.value)

I cannot test this since I don't have xlrd but, I think it will work given the documentation: https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html#sheet.Cell-class

Upvotes: 17

Related Questions