Reputation:
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 :
i have an .xls
and when i use xlrd to get a value i'm just using
sh.cell(0,0)
(assuming that sh is my sheet);
if what is in the cell is a string i get something like text:u'MyName'
and i only want to keep the string 'MyName'
;
if what is in the cell is a number i get something like number:201.0
and i only want to keep the integer 201
.
If anyone can indicate me what i should to only extract the value, formatted as i want, thank you.
Upvotes: 9
Views: 29816
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
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
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
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