Skip to content

Instantly share code, notes, and snippets.

@jkeyes
Created June 27, 2011 10:14
Show Gist options
  • Save jkeyes/1048621 to your computer and use it in GitHub Desktop.
Save jkeyes/1048621 to your computer and use it in GitHub Desktop.
Excel to CSV
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment