-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_excel_sheet
executable file
·34 lines (27 loc) · 1.08 KB
/
extract_excel_sheet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/python
import xlrd
import sys,errno
import csv
import argparse
parser = argparse.ArgumentParser(description='Extract an Excel spreadsheet to a tab-separated file')
parser.add_argument('infile', nargs='?', help='Input file')
parser.add_argument('sheet', nargs='?', help='Sheet index to extract (Zero-indexed, default 0', default=0)
parser.add_argument('outfile', nargs='?', help='File to output to (use - for stdout, default stdout)', default='-')
args = parser.parse_args()
outfile = sys.stdout
if args.outfile == '-':
pass
else:
outfile = open(args.outfile, 'w')
try:
wb = xlrd.open_workbook(args.infile)
sheet = wb.sheet_by_index(int(args.sheet))
c = csv.writer(outfile,delimiter='\t',lineterminator='\n')
num_rows = sheet.nrows
curr_row = 0
while curr_row < num_rows:
c.writerow([ cell.value.encode('utf-8') if isinstance(cell.value, basestring) else int(cell.value) if cell.value==int(cell.value) else cell.value for cell in sheet.row(curr_row)])
curr_row += 1
except IOError as e:
if e.errno == errno.EPIPE:
sys.exit()