Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xls to csv converter

I am using win32.client in python for converting my .xlsx and .xls file into a .csv. When I execute this code it's giving an error. My code is:

def convertXLS2CSV(aFile):     '''converts a MS Excel file to csv w/ the same name in the same directory'''      print "------ beginning to convert XLS to CSV ------"      try:         import win32com.client, os         from win32com.client import constants as c         excel = win32com.client.Dispatch('Excel.Application')          fileDir, fileName = os.path.split(aFile)         nameOnly = os.path.splitext(fileName)         newName = nameOnly[0] + ".csv"         outCSV = os.path.join(fileDir, newName)         workbook = excel.Workbooks.Open(aFile)         workbook.SaveAs(outCSV, c.xlCSVMSDOS) # 24 represents xlCSVMSDOS         workbook.Close(False)         excel.Quit()         del excel          print "...Converted " + nameOnly + " to CSV"     except:         print ">>>>>>> FAILED to convert " + aFile + " to CSV!"  convertXLS2CSV("G:\\hello.xlsx") 

I am not able to find the error in this code. Please help.

like image 784
Lalit Chattar Avatar asked Mar 27 '12 06:03

Lalit Chattar


People also ask

Can we convert XLSX file to CSV?

How to convert a XLSX to a CSV file? Choose the XLSX file that you want to convert. Select CSV as the the format you want to convert your XLSX file to. Click "Convert" to convert your XLSX file.


1 Answers

I would use xlrd - it's faster, cross platform and works directly with the file.

As of version 0.8.0, xlrd reads both XLS and XLSX files.

But as of version 2.0.0, support was reduced back to only XLS.

import xlrd import csv  def csv_from_excel():     wb = xlrd.open_workbook('your_workbook.xls')     sh = wb.sheet_by_name('Sheet1')     your_csv_file = open('your_csv_file.csv', 'wb')     wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)      for rownum in xrange(sh.nrows):         wr.writerow(sh.row_values(rownum))      your_csv_file.close() 
like image 197
Ben Hughes Avatar answered Sep 20 '22 02:09

Ben Hughes