Python xlrd convert integers and strings to floats

I tried to convert the excel file to csv successfully, but it converted all my numbers (even though they were whole or text in the excel file) to float.

I know python reads numbers as floats by default.

Is there a chance to turn all my numbers into strings?

my code is below.

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.

+3


source to share


1 answer


My job was to process the Excel Cell-by-Cell file first through a new nested list and then write that nested list to a CSV file.

Once I have access to the individual cell values, I can convert them to String Data Types, which leave the inner elements of the cell as they are in the CSV file (with the String quotes 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 add these processed cell values ​​to one line and add one line to a nested list that serves as a copy of the original excel input file.

0


source







All Articles