Excel2CSV
Small itch scratched.
import csv
from xlrd import open_workbook
def excel_to_csv(excel_file, include=None):
"""
Convert the data in the excel_file to CSV. If
include is specified, only those named columns
will be included in the CSV.
"""
# open the Excel file
wb = open_workbook(excel_file)
# read each sheet in the file
for s in wb.sheets():
# create a CVS writer per sheet
csv_writer = csv.writer(open("%s.csv" % (s.name), 'wb'))
# what columns are included in the CSV?
include_cols = []
for col in range(s.ncols):
heading = s.cell(0, col).value
if include:
if heading in include:
include_cols.append(col)
else:
include_cols.append(col)
# for each row, write a line of CSV.
for row in range(s.nrows):
rd = []
for col in include_cols:
value = s.cell(row, col).value
rd.append(value)
csv_writer.writerow(rd)
Aided and abetted by xlrd.