Skip to content

Instantly share code, notes, and snippets.

@oiuww09fn
Created September 11, 2014 03:22
Show Gist options
  • Save oiuww09fn/ad28047a671212208df7 to your computer and use it in GitHub Desktop.
Save oiuww09fn/ad28047a671212208df7 to your computer and use it in GitHub Desktop.
read xls, and return line by line.
def read_xls(filepath, encoding="cp1251"):
book = xlrd.open_workbook(filepath)
for sheetid in xrange(book.nsheets):
sheet = book.sheet_by_index(sheetid)
if not sheet:
raise RuntimeError("Sheet %i Not Found" % sheetid)
continue
for i in xrange(sheet.nrows):
row = [""] * sheet.ncols
ctys = sheet.row_types(i)
cvals = sheet.row_values(i)
for j in xrange(sheet.ncols):
cty = ctys[j]
cval = cvals[j]
if cty == xlrd.XL_CELL_NUMBER:
ival = int(cval)
if cval == ival:
cval = ival
else:
cval = "%s" % cval
elif cty == xlrd.XL_CELL_TEXT:
cval = cval.encode('utf-8')
elif cty == xlrd.XL_CELL_DATE:
try:
cval = xlrd.xldate_as_tuple(cval, book.datemode)
except xlrd.XLDateError:
e1, e2 = sys.exc_info()[:2]
cval = "%s:%s" % (e1.__name__, e2)
cty = xlrd.XL_CELL_ERROR
elif cty == xlrd.XL_CELL_ERROR:
cval = xlrd.error_text_from_code.get(
cval,
'<unknown error="" code="" 0x%02x="">' %
cval
)
row[j] = str(cval).decode("utf-8")
yield ", ".join(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment