Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python xlrd transforms integers and strings into floats

I tried succesfully to convers an excel file into csv but it converted all my numbers (despite the fact that they were integers or text in the excel file) to floats.

I know that python reads by default numbers as floats.

is there any chance to turn all my numbers to strings?

my code is bellow

def Excel2CSV(ExcelFile, SheetName, CSVFile):
 import xlrd
 import csv
 workbook = xlrd.open_workbook(ExcelFile)
 worksheet = workbook.sheet_by_name(SheetName)
 csvfile = open(CSVFile, 'wb')
 wr = csv.writer(csvfile, delimiter=';', quoting=csv.QUOTE_NONNUMERIC)

 for rownum in xrange(worksheet.nrows):
     wr.writerow(
         list(x.encode('utf-8') if type(x) == type(u'') else x
              for x in worksheet.row_values(rownum)))

 csvfile.close()

thank you for your time

like image 538
Vagner13 Avatar asked Jul 12 '26 19:07

Vagner13


1 Answers

My work-around has been to treat the Excel file Cell-by-Cell first through a new nested list, and then writing that nested list to a CSV file.

By accessing individual Cell Values, I can convert them to String Data Types which leaves the internals of the cell as-is in the CSV file ( with the String quotation marks removed of course ).

Here's how I access individual Cell Values :

for rownum in xrange(worksheet.nrows):
    for col_num in xrange ( worksheet.ncols ) :
        value = str ( worksheet.row (rownum ) [ column_num ].value )

I append these treated cell values to a single row and append that single row to a nested list that serves as a copy of the original input excel file.

like image 176
RasikhJ Avatar answered Jul 15 '26 09:07

RasikhJ