Python xlrd : how to convert an extracted value?

与世无争的帅哥 提交于 2019-11-27 02:54:39

问题


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.


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!