forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxlsrd
More file actions
executable file
·57 lines (45 loc) · 1.92 KB
/
xlsrd
File metadata and controls
executable file
·57 lines (45 loc) · 1.92 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#! /usr/bin/env python
# Read and print an excel .xls spreadsheet.
# Thanks to http://scienceoss.com/read-excel-files-from-python/
import sys, xlrd
def print_sheet(sheetname, sh):
# Gnumeric makes null sheets, with 0 rows and 0 columns.
# Guard against division by zero in gnumeric spreadsheets:
if not sh or sh.ncols <= 0:
print("Null sheet", sheetname)
return
print("===== sheet", sheetname, ": rows", sh.nrows, "cols", sh.ncols)
# set a maximum on any one column.
# Ideally this would be smarter,
# and would let one long row expand if the rest were shorter.
maxlen = 80 / sh.ncols
# Get max len for each col
maxstr = [1] * sh.ncols
for rownum in range(sh.nrows):
for colnum in range(sh.ncols):
# Figure out how many characters this cell needs.
val = sh.cell(rownum, colnum).value
# This gets lots of null strings, so filter them out:
if not val:
continue
#print "type:", type(val), val
slen = len(str(val))
#if slen > maxlen: slen = maxlen
if slen > maxstr[colnum]:
maxstr[colnum] = slen
fmt = ""
for colnum in range(sh.ncols):
fmt += "%%-%ds" % (maxstr[colnum] + 1)
for rownum in range(sh.nrows):
# Should get the charset from the environment, but it's not clear
# even that is enough. In practice, this works to stdout without
# needing the encode, but to pipe through grep or redirect to a
# file it needs the encode.
print((fmt % tuple(map(str,
sh.row_values(rownum)))).encode(sys.getdefaultencoding(),
'backslashreplace'))
for filename in sys.argv[1:]:
wb = xlrd.open_workbook(filename)
#sh = wb.sheet_by_index(0)
for sheetname in wb.sheet_names():
print_sheet(sheetname, wb.sheet_by_name(sheetname))