#!/usr/bin/env python """ This function converts the first sheet in an Excel file into a csv file Versions of Excel supported: 2003, 2002, XP, 2000, 97, 95 Download the xlrd package from http://www.lexicon.net/sjmachin/xlrd.htm Windows: download and run this installer xlrd-0.6.1.win32.exe. Linux: download and unzip the zip file, and do "sudo python setup.py install". Usage: xls2csv filename.xls filename.csv Sheet name is added as the first column in the scv file """ __author__ = "Tom Luo" __version__ = "$Revision 0.1 $" __date__ ="$Date: 2010/08/06 14:11 CST$" import xlrd import csv import string def xls2csv(excel_filename,csv_filename): try: book = xlrd.open_workbook(excel_filename) print "The number of worksheets: %d" % book.nsheets sheet_name = book.sheet_names()[0].split(' ')[0] #The first sheet sh = book.sheet_by_index(0) print "Sheet name:", sh.name, " | Number of rows:", sh.nrows, " | Number of columns:", sh.ncols csv_file = open(csv_filename,'w') w = csv.writer(csv_file, csv.excel) for row in range(sh.nrows): cell_types = sh.row_types(row) for col in range(sh.ncols): if cell_types[col] == xlrd.XL_CELL_DATE: cell_val = datetime.datetime(*xlrd.xldate_as_tuple(sh.cell_value(row,col), book.datemode)) else: cell_val = str(sh.cell_value(row,col)).encode('utf8') this_row.append(cell_val) if row == 0 or (row > 0 and this_row[1].isdigit()): w.writerow(this_row) print "%s has been created" % csv_filename except IOError: print "IOError: Please ensure %s exists" % excel_filename if __name__ == "__main__": import sys if len(sys.argv) == 2: excel_file = sys.argv[1] csv_file = sys.argv[1].split('.')[0] + '.csv' xls2csv(excel_file, csv_file) elif len(sys.argv) == 3: xls2csv(sys.argv[1],sys.argv[2]) else: print "Usage(Linux): xls2csv filename.xls filename.csv" print "OR" print "Usage(Windows): python xl2csv filename.xls filename.csv" print "OR" print "Usage: xls2csv filename.xls"