xlsusers.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import xlrd
  2. import datetime
  3. import uuid
  4. import os
  5. def process_cell(table,i,j):
  6. _temp=table.cell(i,j)
  7. if _temp.ctype==1:
  8. return _temp.value
  9. if _temp.ctype==2:
  10. return str(int(_temp.value))
  11. #raise "Error xls!"
  12. def processxls(FILE):
  13. BASE_DIR = os.path.dirname(os.path.dirname(__file__))
  14. xlsname = os.path.join(BASE_DIR, 'uploads', '%s.xls' % str(uuid.uuid4()))
  15. destination = open(xlsname,'wb')
  16. for chunk in FILE.chunks():
  17. destination.write(chunk)
  18. destination.close()
  19. data = xlrd.open_workbook(xlsname)
  20. table = data.sheet_by_index(0)
  21. head = table.row_values(0)
  22. assert len(head)==7
  23. assert head[0].strip()==u'\u5b66\u53f7'
  24. assert head[1].strip()==u'\u7528\u6237\u540d'
  25. assert head[2].strip()==u'\u59d3\u540d'
  26. assert head[3].strip()==u'\u6027\u522b'
  27. assert head[4].strip()==u'\u5bc6\u7801'
  28. assert head[5].strip()==u'\u5206\u7ec4\u53f7'
  29. assert head[6].strip()==u'\u751f\u65e5'
  30. rets=[]
  31. for i in range(table.nrows-1):
  32. col = table.row_values(i+1)
  33. sid=str(int(col[0]))
  34. username=col[1]
  35. name=process_cell(table,i+1,2)
  36. sex=col[3]
  37. password=process_cell(table,i+1,4)
  38. cid=str(int(col[5]))
  39. if table.cell(i+1,6).ctype==3:
  40. birthday = datetime.date(*xlrd.xldate_as_tuple(table.cell(i+1,6).value,data.datemode)[:3])
  41. else:
  42. try:
  43. birthday = datetime.datetime.strptime(process_cell(table,i+1,6), "%Y-%m-%d").date()
  44. except:
  45. try:
  46. birthday = datetime.datetime.strptime(process_cell(table,i+1,6), "%Y%m%d").date()
  47. except:
  48. pass
  49. #raise "Error xls!"
  50. rets.append((sid,username,name,sex,password,cid,birthday))
  51. return rets