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 ?

Julien
  • 699
  • 3
  • 14
  • 30
  • 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'`. – Martijn Pieters Mar 01 '13 at 12:57
  • Actually it works ! And yes you're right, I forgot to rename correctly the xls. Thank you Martijn ! – Julien Mar 01 '13 at 13:20

1 Answers1

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')
Fernando Freitas Alves
  • 3,709
  • 3
  • 26
  • 45
  • The indentation works pretty well. But thank you for the help ! – Julien Mar 01 '13 at 13:20
  • 1
    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: http://stackoverflow.com/a/9137934/1317713 to auto-adjust column width. – Leonid Sep 13 '15 at 20:06