Django 使用xlwt實現從後臺mysql匯出資料到excel表
阿新 • • 發佈:2018-12-12
1. pip install xlwt #安裝xlwt 模組
2. 新建excel.py
import xlwt #from io import StringIO from django.db import connection from django.shortcuts import HttpResponse try: import cStringIO as stringIOModule except ImportError: try: import StringIO as stringIOModule except ImportError: import io as stringIOModule #from MySQLdb.cursors import DictCursor #conn = MySQLdb.connect(host='192.168.2.4', user='root', passwd='zj88friend', db='zz91crm', port=3306, charset='utf8', # cursorclass=MySQLdb.cursors.DictCursor) # 其中cursorclass設定返回資料型別為字典 #cur = conn.cursor() # 獲取遊標 def exc_sql(sql): cursor = connection.cursor() cursor.execute(sql) result = cursor.fetchall() return result def export_xls(request): response = HttpResponse(content_type='application/vnd.ms-excel') # 指定返回為excel檔案 response['Content-Disposition'] = 'attachment;filename=export_list.xls' # 指定返回檔名 wb = xlwt.Workbook(encoding='utf-8') # 設定編碼型別為utf8 hosttype_id1 = 1 # workstation hosttype_id2 = 2 #laptop hosttype_id3 = 3 #desktop hosttype_id4 = 4 #server hosttype_id5 = 5 #switch host_status1 = "in use" # was using by users host_status2 = "inventory" # in space , no user host_status3 = "P-Dispose" # apply for disposal,waiting for approval host_status4 = "disposed" # disposed , but it is till in use if request.method=='GET': id=request.GET.get('id') if id == '1': sql = """select p.host_name ,p.service_tag,h.name , p.host_model,p.receive_date , CURDATE(),TIMESTAMPDIFF(YEAR,p.receive_date,CURDATE()) , \ TIMESTAMPDIFF(MONTH,p.receive_date,CURDATE())%%12 ,u.full_name , d.dept_name,p.studio, s.sitename as location,p.host_status, \ p.asset_code,p.remark from deviceman_pc_list as p, deviceman_user_list as u, deviceman_dept_list as d, deviceman_hosttype as h, deviceman_site as s \ where p.user_list_id=u.id and u.dept_list_id=d.id and p.site_id=s.id and p.hosttype_id=h.id and ( hosttype_id ='%s' or hosttype_id='%s' or hosttype_id= '%s' ) \ and (host_status = '%s' or host_status='%s' )order by h.id, p.host_name """ % (hosttype_id1, hosttype_id2, hosttype_id3, host_status1, host_status2) sheet = wb.add_sheet(u'01 Deployed') # excel裡新增類別 if id == '2': sql = """select p.host_name ,p.service_tag,h.name , p.host_model,p.receive_date , CURDATE(),TIMESTAMPDIFF(YEAR,p.receive_date,CURDATE()) , \ TIMESTAMPDIFF(MONTH,p.receive_date,CURDATE())%%12 ,u.full_name , d.dept_name,p.studio, s.sitename as location,p.host_status, \ p.asset_code,p.remark from deviceman_pc_list as p, deviceman_user_list as u, deviceman_dept_list as d, deviceman_hosttype as h, deviceman_site as s \ where p.user_list_id=u.id and u.dept_list_id=d.id and p.site_id=s.id and p.hosttype_id=h.id and ( hosttype_id ='%s' ) \ and (host_status = '%s' or host_status='%s' )order by h.id, p.host_name """ % (hosttype_id4, host_status1, host_status2) sheet = wb.add_sheet(u'02 Servers') # excel裡新增類別 if id == '3': IBM_ASS='%CNSHZ1BPC%' sql = """select p.host_name ,p.service_tag,h.name , p.host_model,p.receive_date , CURDATE(),TIMESTAMPDIFF(YEAR,p.receive_date,CURDATE()) , \ TIMESTAMPDIFF(MONTH,p.receive_date,CURDATE())%%12 ,u.full_name , d.dept_name,p.studio, s.sitename as location,p.host_status, \ p.asset_code,p.remark from deviceman_pc_list as p, deviceman_user_list as u, deviceman_dept_list as d, deviceman_hosttype as h, deviceman_site as s \ where p.user_list_id=u.id and u.dept_list_id=d.id and p.site_id=s.id and p.hosttype_id=h.id and ( hosttype_id ='%s' ) \ and host_name like '%s' order by h.id, p.host_name """ % (hosttype_id1,IBM_ASS) sheet = wb.add_sheet(u'03 IBM Assets') # excel裡新增類別 if id == '4': sql = """select p.host_name ,p.service_tag,h.name , p.host_model,p.receive_date , CURDATE(),TIMESTAMPDIFF(YEAR,p.receive_date,CURDATE()) , \ TIMESTAMPDIFF(MONTH,p.receive_date,CURDATE())%%12 ,u.full_name , d.dept_name,p.studio, s.sitename as location,p.host_status, \ p.asset_code,p.remark from deviceman_pc_list as p, deviceman_user_list as u, deviceman_dept_list as d, deviceman_hosttype as h, deviceman_site as s \ where p.user_list_id=u.id and u.dept_list_id=d.id and p.site_id=s.id and p.hosttype_id=h.id and ( hosttype_id ='%s' or hosttype_id='%s' or hosttype_id= '%s' ) \ and (host_status = '%s' )order by h.id, p.host_name """ % (hosttype_id1, hosttype_id2, hosttype_id3, host_status3) sheet = wb.add_sheet(u'04 Pending Disposal') # excel裡新增類別 if id == '5': age_year=4 # 使用期超過四年的電腦 public_user='Public' # public 使用者名稱,在匯出清單時要排隊公用電腦 sql = """select p.host_name ,p.service_tag,h.name , p.host_model,p.receive_date , CURDATE(),TIMESTAMPDIFF(YEAR,p.receive_date,CURDATE()) , \ TIMESTAMPDIFF(MONTH,p.receive_date,CURDATE())%%12 ,u.full_name , d.dept_name,p.studio, s.sitename as location,p.host_status, \ p.asset_code,p.remark from deviceman_pc_list as p, deviceman_user_list as u, deviceman_dept_list as d, deviceman_hosttype as h, deviceman_site as s \ where p.user_list_id=u.id and u.dept_list_id=d.id and p.site_id=s.id and p.hosttype_id=h.id and ( hosttype_id ='%s' or hosttype_id='%s' or hosttype_id= '%s' ) \ and (host_status = '%s' ) and u.user_name<>'%s' and TIMESTAMPDIFF(YEAR,p.receive_date,CURDATE())>=%s order by h.id, p.host_name """ % (hosttype_id1, hosttype_id2, hosttype_id3, host_status1,public_user,age_year) sheet = wb.add_sheet(u'05 Refresh List') # excel裡新增類別 else: print('error for export excel') #conn.cursor().execute(sql) # 執行sql語句 #conn.cursor().fetchall() # 獲取查詢結果 data_list = exc_sql(sql) #sheet = wb.add_sheet(u'清單') # excel裡新增類別 style_heading = xlwt.easyxf(""" font: name Calibri, colour_index white, bold on, height 0xA0; align: wrap off, vert center, horiz center; pattern: pattern solid, fore-colour 0x19; borders: left THIN, right THIN, top THIN, bottom THIN; """ ) style_body = xlwt.easyxf(""" font: name Calibri, bold off, height 0XA0; align: wrap on, vert center, horiz left; borders: left THIN, right THIN, top THIN, bottom THIN; """ ) style_num_col = xlwt.easyxf(""" font: name Arial, bold off, height 0XA0; align: wrap on, vert center, horiz left; borders: left THIN, right THIN, top THIN, bottom THIN; """ ) style_green = xlwt.easyxf(" pattern: pattern solid,fore-colour 0x11;") style_red = xlwt.easyxf(" pattern: pattern solid,fore-colour 0x0A;") fmts = [ 'M/D/YY', 'D-MMM-YY', 'D-MMM', 'MMM-YY', 'h:mm AM/PM', 'h:mm:ss AM/PM', 'h:mm', 'h:mm:ss', 'M/D/YY h:mm', 'mm:ss', '[h]:mm:ss', 'mm:ss.0', ] style_body.num_format_str = fmts[0] sheet.write(0, 0, 'Host Name', style_heading) sheet.write(0, 1, 'Service Tag', style_heading) sheet.write(0, 2, 'Type', style_heading) sheet.write(0, 3, 'Model', style_heading) sheet.write(0, 4, 'Receive Date', style_heading) sheet.write(0, 5, 'Today', style_heading) sheet.write(0, 6, 'Age(Yr)', style_heading) sheet.write(0, 7, 'Age(M)', style_heading) sheet.write(0, 8, 'Users', style_heading) sheet.write(0, 9, 'BL', style_heading) sheet.write(0, 10, 'Studio(if Applicable)', style_heading) sheet.write(0, 11, 'Location', style_heading) sheet.write(0, 12, 'Status', style_heading) sheet.write(0, 13, 'FA Code', style_heading) sheet.write(0, 14, 'Remark', style_heading) row = 1 for list in data_list: sheet.write(row, 0, list[0], style_body) sheet.write(row, 1, list[1], style_body) sheet.write(row, 2, list[2], style_body) sheet.write(row, 3, list[3], style_body) sheet.write(row, 4, list[4], style_body) sheet.write(row, 5, list[5], style_body) sheet.write(row, 6, list[6], style_num_col ) sheet.write(row, 7, list[7], style_num_col) sheet.write(row, 8, list[8], style_body) sheet.write(row, 9, list[9], style_body) sheet.write(row, 10, list[10], style_body) sheet.write(row, 11, list[11], style_body) sheet.write(row, 12, list[12], style_body) sheet.write(row, 13, list[13], style_num_col) sheet.write(row, 14, list[14], style_body) row = row + 1 #output = StringIO.StringIO() output = stringIOModule.BytesIO() wb.save(output) output.seek(0) response.write(output.getvalue()) return response
3. 新建模板檔案report.html
<!DOCTYPE html> <html lang="en"> <head> <title>AECOM IT Device Manager Tools</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/static/jquery-3.3.1.js"></script> <script type="text/javascript"> function resign_confirm(var1,var2){ var result = confirm('清除計算機'+var2+'的使用者資訊?確認請點[OK]!或者點[Cancel]取消'); if(result){ alert('確定清除!'); window.navigate('update_pc?id='+var1); }else{ alert('不清除!'); } } function collect_confirm(var1,var2){ var result = confirm('回收計算機'+var2+'、清除使用者資訊?確認請點[OK]!或者點[Cancel]取消'); if(result){ alert('確定回收!'); window.navigate('update_pc?id='+var1+'&action=collect'); }else{ alert('不回收!'); } } function dispose_confirm(var1,var2){ var result = confirm('申請報廢計算機'+var2+'、清除使用者資訊?確認請點[OK]!或者點[Cancel]取消'); if(result){ alert('確定申請報廢!'); window.navigate('update_pc?id='+var1+'&action=dispose'); }else{ alert('不申請!'); } } function search_confirm(){ var vpcid1 = document.getElementsByName("pcid"); if (vpcid1.length=0) { alert('不回收!'); } } $(document).ready(function(){ $("#input1").click(function(){ $("#p1").toggle("slow"); }); }); </script> </head> <body> <div class="container"> {% include "headbase.html" %} <a href="#" class="list-group-item active" > 當前模組:清單報表->匯出裝置清單 </a> <div class="row"> <div class="col-sm-12"> <div> <p> <form action="{{ acton }}?pcid={{ pcid }}" method="POST" novalidate="novalidate"> <label> Site Code:</label> <input type="text" id="sitecode" name="sitecode" value="{{id }}" /> </form> </p></div> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>#</th> <th>清單名稱</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>01 Deployed (工作站、筆記本、桌上型電腦清單)</td> <td> <input type="button" value="匯出Excel" onclick="window.navigate('exportxls?id=1')" /> </td> </tr> <tr> <td>2</td> <td>02 Servers (伺服器清單)</td> <td> <input type="button" value="匯出Excel" onclick="window.navigate('exportxls?id=2')" /> </td> </tr> <tr> <td>3</td> <td>03 IBM Assets (IBM資產清單)</td> <td> <input type="button" value="匯出Excel" onclick="window.navigate('exportxls?id=3')" /> </td> </tr> <tr> <td>4</td> <td>04 Pending Disposal (待報廢資產清單)</td> <td> <input type="button" value="匯出Excel" onclick="window.navigate('exportxls?id=4')" /> </td> </tr> <tr> <td>5</td> <td>05 Refresh list (超過四年且有使用者使用的電腦)</td> <td> <input type="button" value="匯出Excel" onclick="window.navigate('exportxls?id=5')" /> </td> </tr> {% for user_list in users %} <tr> <td>{{ forloop.counter }}</td> <td>{{ user_list.user_name }}</td> <td> <input type="button" value="匯出Excel" onclick="" /> </td> </tr> {% endfor %} </tbody> </table> </div> <p>再牛逼的夢想,也抵不住你傻逼似的堅持!</p> </div> </div> </div> </body> </html>