Python xlrd: how to convert the extracted value?

Well, I have a question, how do I feel that they answered me several times, from what I found here. However, as a beginner, I cannot figure out how to perform a truly basic operation.

Here's the thing:

  • I have .xls , and when I use xlrd to get the value, I just use sh.cell(0,0) (assuming sh is my sheet);

  • if there is a row in the cell, I get something like text:u'MyName' , and I want to save the string 'MyName' ;

  • if there is a number in the cell, I get something like number:201.0 , and I only want to save the integer 201 .

If someone can tell me that I only need to extract the value formatted as I want, thanks.

+6
source share
4 answers

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

You must try:

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

I cannot verify this since I do not have xlrd, but I think it will work based on the documentation: https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html # sheet.Cell-class

+12
source

You can also just extract the values ​​using xlrd rather than returning the full Excel cell:

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

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

You can use slices with row_values ​​(and similarly for columns). So, to get values ​​from a whole 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 to use xlrd - but it worked for me.

+3
source

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

0
source

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

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

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

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

Source: https://habr.com/ru/post/906293/


All Articles