Vagner13
Vagner13

Reputation: 61

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

Upvotes: 3

Views: 3511

Answers (1)

RasikhJ
RasikhJ

Reputation: 611

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.

Upvotes: 1

Related Questions