问题
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 usingsh.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 integer201
.
If anyone can indicate me what i should to only extract the value, formatted as i want, thank you.
回答1:
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
回答2:
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.
回答3:
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')
回答4:
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.
来源:https://stackoverflow.com/questions/8909342/python-xlrd-how-to-convert-an-extracted-value