-2

I'm coming from the xls to csv converter . It helps me to converting excel sheets to csv files.

I've integer values in my excel-sheets, while I'm writing them into csv files, they got converted into float values. example.

1 > 1.0

My data is something like,

no  name   marks  friend
01  kirk    190   sandy
02  stark   100   kim

all the above integer becomes float.

no    name    marks   friend
01.0  kirk    190.0    sandy
02.0  stark   100.0    kim

Is there any solution to override the issue?

code for reference,

# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys

def csv_from_excel(excel_file):
    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        your_csv_file = open(''.join([worksheet_name,'.csv']), 'wb')
        wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

        for rownum in xrange(worksheet.nrows):
            wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])
        your_csv_file.close()

if __name__ == "__main__":
    csv_from_excel(sys.argv[1])
Community
  • 1
  • 1

1 Answers1

2

You need to be more careful in this part:

[unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)]

You transform entry to a string (unicode object) right away, and then encode this string to utf-8 representation. Instead, you should inspect entry and deal with it on a case-to-case basis.

The documentation is a little thin: http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Sheet.row_values-method -- I guess entry is of type Cell (http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Cell-class), but I guess you need to experiment.

Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130