main.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import io
  2. import xlwt
  3. import pymysql
  4. from app import app
  5. from db import mysql
  6. from flask import Flask, Response, render_template
  7. @app.route('/')
  8. def upload_form():
  9. return render_template('download.html')
  10. @app.route('/download/report/excel')
  11. def download_report():
  12. conn = None
  13. cursor = None
  14. try:
  15. conn = mysql.connect()
  16. cursor = conn.cursor(pymysql.cursors.DictCursor)
  17. cursor.execute("SELECT emp_id, emp_first_name, emp_last_name, emp_designation FROM employee")
  18. result = cursor.fetchall()
  19. #output in bytes
  20. output = io.BytesIO()
  21. #create WorkBook object
  22. workbook = xlwt.Workbook()
  23. #add a sheet
  24. sh = workbook.add_sheet('Employee Report')
  25. #add headers
  26. sh.write(0, 0, 'Emp Id')
  27. sh.write(0, 1, 'Emp First Name')
  28. sh.write(0, 2, 'Emp Last Name')
  29. sh.write(0, 3, 'Designation')
  30. idx = 0
  31. for row in result:
  32. sh.write(idx+1, 0, str(row['emp_id']))
  33. sh.write(idx+1, 1, row['emp_first_name'])
  34. sh.write(idx+1, 2, row['emp_last_name'])
  35. sh.write(idx+1, 3, row['emp_designation'])
  36. idx += 1
  37. workbook.save(output)
  38. output.seek(0)
  39. return Response(output, mimetype="application/ms-excel", headers={"Content-Disposition":"attachment;filename=employee_report.xls"})
  40. except Exception as e:
  41. print(e)
  42. finally:
  43. cursor.close()
  44. conn.close()
  45. if __name__ == "__main__":
  46. app.run()