Skip to content
Browse files

Display a .xls spreadsheet as a table in plaintext

  • Loading branch information...
1 parent 5922c76 commit 624bc1f554e9d961dc917e91ff0eaef1276f9110 @akkana committed
Showing with 52 additions and 0 deletions.
  1. +52 −0 xlsrd
View
52 xlsrd
@@ -0,0 +1,52 @@
+#! /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.
+ # This would be easy except for Python's
+ 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(unicode(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) :
+ print fmt % tuple(map(unicode, sh.row_values(rownum)))
+
+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))
+

0 comments on commit 624bc1f

Please sign in to comment.
Something went wrong with that request. Please try again.