Hi everyone!

I'm trying to make a function in Python that converts a csv file into a xls file.
I have to convert about 500 files so you understand that I need it to be as clean as possible.

This is the code I wrote, just for one file later on I'll execute it on every file of the folder:

from win32com.client import Dispatch
import os

fpath = 'C:\\usr\\PRG_PYTHON\\TestFiles\\File1.csv'

def ConvertCSVToXLS(fpath):
    excel = Dispatch('Excel.Application')

    (filedir, filename) = os.path.split(fpath)
    (shortname,extension) = os.path.splitext(filename)
    newname =shortname + ".xls"
    outCSV = os.path.join(filedir, newname)
    workbook = excel.Workbooks.Open(fpath)
    workbook.SaveAs(outCSV, FileFormat=24) # 6 represents CSV file
    del excel

    print "...Converted " + shortname + " to xls"


When I execute this file, everything seems to be working just fine. But when I open the file though I get a lot of messages and I have to save the file in the right format because it stil see's the file as a csv?!?
Does anyone know how to takkle this problem.

When I do it manually (open .csv file in Excel and save it in .xls) it works as a charme.

Many thx in front!

hello Please try the below code its working for me!!!!

#CSV to Excel try
# open_an_existing_workbook.py
# Open an existing workbook

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'D:\Documents and Settings\palappr\Desktop\test\New\CPR sani bagavan.csv')
excel.Visible = False
outxl=r'D:\Documents and Settings\palappr\Desktop\test\New\CPR sani bagavan.xls'
wb.SaveAs(outxl, FileFormat=1)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.