Created
October 21, 2013 11:17
-
-
Save carlosescri/7082236 to your computer and use it in GitHub Desktop.
Requires the xlrd library to read Excel 97 .xls files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import re | |
from os import path | |
from optparse import OptionParser | |
from xlrd import open_workbook | |
def run(): | |
parser = OptionParser("%prog [options] input.xls") | |
parser.add_option('-c', '--columns', action='store', dest='columns', type='string', default="", help="Columnas a exportar (por defecto todas). Ej: --columns='4,3,2,5,1,0'") | |
options, args = parser.parse_args() | |
if len(args) != 1: | |
parser.print_usage() | |
return 1 | |
if not path.isfile(args[0]): | |
parser.error("%s no existe." % args[0]) | |
return 2 | |
wb = open_workbook(args[0], on_demand=True, encoding_override="utf-8") | |
ws = wb.sheet_by_index(0) | |
if options.columns: | |
columns = [int(x.strip()) for x in options.columns.split(',')] | |
else: | |
columns = [x for x in range(0, ws.ncols)] | |
for i in range(0, ws.nrows): | |
values = [] | |
for j in columns: | |
if j >= 0: | |
val = ws.cell(i, j).value | |
if isinstance(val, unicode): | |
val = re.sub(r'(\n|\r|["])+', ' ', val.encode('utf-8').strip()) | |
elif isinstance(val, float): | |
val = int(val) | |
else: | |
val = '' | |
values.append('"%s"' % val) | |
print ",".join(values) | |
# sys.stdout.write(u"%s\n" % ";".join(values)) | |
return 0 | |
if __name__ == "__main__": | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment