xlspasswd.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import xlrd,xlwt
  2. import datetime
  3. import uuid
  4. import os
  5. from django.conf import settings
  6. def process_cell(table,i,j):
  7. _temp=table.cell(i,j)
  8. if _temp.ctype==1:
  9. return _temp.value
  10. if _temp.ctype==2:
  11. return str(int(_temp.value))
  12. #raise "Error xls!"
  13. def randompass():
  14. return str(uuid.uuid4()).replace('-','')[:10]
  15. def GeneratePasswdToXls(FILE):
  16. BASE_DIR = os.path.dirname(os.path.dirname(__file__))
  17. wrxlsname = 'pwdout-%s.xls' % str(uuid.uuid4())
  18. wrxlspath = os.path.join(settings.MEDIA_ROOT,'xls',wrxlsname )
  19. xlsname = os.path.join(BASE_DIR, 'uploads', '%s.xls' % str(uuid.uuid4()))
  20. destination = open(xlsname,'wb')
  21. for chunk in FILE.chunks():
  22. destination.write(chunk)
  23. destination.close()
  24. data = xlrd.open_workbook(xlsname)
  25. table = data.sheet_by_index(0)
  26. head = table.row_values(0)
  27. assert len(head)==7
  28. assert head[0].strip()==u'\u5b66\u53f7'
  29. assert head[1].strip()==u'\u7528\u6237\u540d'
  30. assert head[2].strip()==u'\u59d3\u540d'
  31. assert head[3].strip()==u'\u6027\u522b'
  32. assert head[4].strip()==u'\u5bc6\u7801'
  33. assert head[5].strip()==u'\u5206\u7ec4\u53f7'
  34. assert head[6].strip()==u'\u751f\u65e5'
  35. rwb = xlwt.Workbook(encoding='utf-8')
  36. rsh = rwb.add_sheet('Sheet1')
  37. rsh.write(0,0,u'\u5b66\u53f7')
  38. rsh.write(0,1,u'\u7528\u6237\u540d')
  39. rsh.write(0,2,u'\u59d3\u540d')
  40. rsh.write(0,3,u'\u6027\u522b')
  41. rsh.write(0,4,u'\u5bc6\u7801')
  42. rsh.write(0,5,u'\u5206\u7ec4\u53f7')
  43. rsh.write(0,6,u'\u751f\u65e5')
  44. for i in range(table.nrows-1):
  45. col = table.row_values(i+1)
  46. username=col[1]
  47. sid=str(int(col[0]))
  48. name=process_cell(table,i+1,2)
  49. sex=col[3]
  50. password=randompass()
  51. cid=str(int(col[5]))
  52. if table.cell(i+1,6).ctype==3:
  53. birthday = datetime.date(*xlrd.xldate_as_tuple(table.cell(i+1,6).value,data.datemode)[:3])
  54. else:
  55. try:
  56. birthday = datetime.datetime.strptime(process_cell(table,i+1,6), "%Y-%m-%d").date()
  57. except:
  58. try:
  59. birthday = datetime.datetime.strptime(process_cell(table,i+1,6), "%Y%m%d").date()
  60. except:
  61. pass
  62. rsh.write(i+1,0,sid)
  63. rsh.write(i+1,1,username)
  64. rsh.write(i+1,2,name)
  65. rsh.write(i+1,3,sex)
  66. rsh.write(i+1,4,password)
  67. rsh.write(i+1,5,cid)
  68. rsh.write(i+1,6,birthday.strftime('%Y%m%d'))
  69. rwb.save(wrxlspath)
  70. return wrxlsname