1

I'd like to open multiple csv files from a list and then convert them into xls files.

I made that code :

import sys, csv, xlwt

files = ['/home/julien/excel/csv/ABORD2.csv']

for i in files:
    f=open(i, 'rb')
    g = csv.reader ((f), delimiter=";")
    workbook=xlwt.Workbook()
    sheet= xlwt.Workbook()
    sheet = workbook.add_sheet("Sheet 1")

    for rowi, row in enumerate(g):
        for coli, value in enumerate(row):
            sheet.write(rowi,coli,value)
        workbook.save(i + ".xls")

My xls files are created.But in both of them I only have the path of the xls. For example for the file ABORD.xls only the following expression is written :

'/home/julien/excel/csv/ABORD2.xls'

Would you have any suggestions ?

2
  • Your code, at first glance, looks correct to me. Moreover, there is no variable in the example code you give here that would ever be equal to '/home/julien/excel/csv/ABORD2.xls'; only '/home/julien/excel/csv/ABORD2.csv.xls'. Commented Mar 1, 2013 at 12:57
  • Actually it works ! And yes you're right, I forgot to rename correctly the xls. Thank you Martijn ! Commented Mar 1, 2013 at 13:20

1 Answer 1

4

Sir, you're creating two Workbooks unnecessairly and you're saving the workbook with wrong identation

import csv, xlwt

files = ['test.csv']

for i in files:
    f=open(i, 'rb')
    g = csv.reader ((f), delimiter=";")
    wbk= xlwt.Workbook()
    sheet = wbk.add_sheet("Sheet 1")

    for rowi, row in enumerate(g):
        for coli, value in enumerate(row):
            sheet.write(rowi,coli,value)

    wbk.save(i + '.xls')
Sign up to request clarification or add additional context in comments.

2 Comments

The indentation works pretty well. But thank you for the help !
Worked for me as well. I easily modified it to output a single Excel file with multiple worksheets in it - initialized the workbook once, outside of the for loop and created differently-named sheets inside of the loop. I used this answer: stackoverflow.com/a/9137934/1317713 to auto-adjust column width.

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.