Vick Peh
Vick Peh

Reputation: 67

Converting xls to csv in python

I've successfully converted xls to csv, but I've a problem. It seems normal in the csv file itself but when I run the output, everything is wrong.

changeWb = xlrd.open_workbook('test.xls')
sh = changeWb.sheet_by_name('detail')
csv_file = open('test2.csv', 'wb')
wr = csv.writer(csv_file, quoting=csv.QUOTE_NONE)
for rownum in xrange(sh.nrows):
    wr.writerow([unicode(entry).encode("utf-8") for entry in sh.row_values(rownum)])
csv_file.close()

I don't have any csv files at the start, opening a csv_file is actually opening a new file freshly. The old output was:

['001', '1387533864.0', '1387575618.0']
['003', '1387534098.0', '1387573600.0']

I need something like:

['1', '1387533864', '1387575618']    
['3', '1387534098', '1387573600']

The bottom output is after I goes into the file, and save as csv(comma delimted). Please advice on how I can get the bottom result using python.

Upvotes: 1

Views: 1653

Answers (1)

falsetru
falsetru

Reputation: 369394

Conver the values to int first:

wr.writerow(sh.row_values(0))
for rownum in xrange(1, sh.nrows):
    wr.writerow([str(int(entry)) for entry in sh.row_values(rownum)])
    #                ^^^

Upvotes: 2

Related Questions