1

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.

1 Answer 1

2

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)])
    #                ^^^
Sign up to request clarification or add additional context in comments.

8 Comments

Hi, thanks for the reply. My row 1 is actually string, followed by int from row 2 onwards, so I can't convert all values into int
@VickPeh, Write header outside the loop. I updated the answer code.
this is the error I received: ValueError: invalid literal for int() with base 10: '1387533864.0'
@VickPeh, How about str(int(float(entry))) instead of str(int(entry))?
@VickPeh, If entry is all string, you can use entry.partition('.')[0]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.