def convert_excel_to_csv(input_excel_file,
output_csv_file_path=None, return_csv_file=False):
"""
Takes the excel file path as input and converts
into csv file and if we select return_csv_file as
True returns csv file else
returns csv file object
Arguments:
1. input_excel_file: It is a excel file path
which is to be converted into csv file
2. output_csv_file_path: If user gives the output csv path,
then creating csv file at that path else creating a csv file
in the directory from where he have given excel file.
3. return_csv_file: If the user selects return_csv_file as True,
returning the output csv file else returning the object.
Returns:
Returns the csv file path if user selects
return_csv_file as True else returns the object.
"""
try:
if output_csv_file_path is None:
if ".xlsx" in input_excel_file:
ret_csv_file = input_excel_file.replace(".xlsx", ".csv")
else:
ret_csv_file = input_excel_file.replace(".xls", ".csv")
else:
ret_csv_file = output_csv_file_path
wb = xlrd.open_workbook(input_excel_file)
sh = wb.sheet_by_index(0)
csv_file = open(ret_csv_file, 'wb+')
wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
for rownum in xrange(sh.nrows):
row_val = sh.row_values(rownum)
for index, value in enumerate(row_val):
if sh.cell(rownum, index).ctype == 3:
year, month, day, hour, minute, sec = xlrd.xldate_as_tuple(
value, wb.datemode)
date_format = "%02d/%02d/%04d" % (month, day, year)
row_val[index] = date_format
wr.writerow(row_val)
if return_csv_file:
csv_file.close()
csv_file = ret_csv_file
else:
csv_file = csv_file
except Exception as exception:
print_exception(exception)
csv_file = None
return csv_file
评论列表
文章目录