• bootstrap-table实现分页、导出数据至excel


    一、导入相关依赖

    <!-- css -->

    <link rel="stylesheet" href="{% static 'app/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'app/css/bootstrap-table.min.css' %}">

    <!-- js -->
    <script src="{% static 'version/js/jquery-3.4.1.min.js' %}"></script>
    <!-- popper.js 不知道有啥用-->
    <script src="{% static 'version/js/popper-1.14.7.min.js' %}" ></script>
    <script src="{% static 'version/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'version/js/bootstrap-table.min.js' %}"></script>
    <script src="{% static 'version/js/bootstrap-table-zh-CN.min.js' %}"></script>
    <script src="{% static 'version/js/bootstrap-table-export.min.js' %}"></script>
    <script src="{% static 'version/js/tableExport-1.10.19.min.js' %}"></script>
    <!-- 图标、字体库 :决定表格右上角的图标是否显示-->
    <script src="{% static 'version/js/font-awesome/all.min.js' %}"></script>

      1 {% load static %}
      2 
      3 <!DOCTYPE html>
      4 <html>
      5     <head>
      6         {% load bootstrap4 %}
      7         {% bootstrap_css %}
      8         {% bootstrap_javascript %}
      9         
     10         <meta charset="UTF-8">      
     11         
     12         <!-- css -->
     13         <link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
     14         <link rel="stylesheet" href="{% static 'app/css/bootstrap.min.css' %}">
     15         <link rel="stylesheet" href="{% static 'app/css/bootstrap-table.min.css' %}">
     16         
     17         <!-- js -->
     18         <script src="{% static 'app/js/jquery-3.4.1.min.js' %}"></script>
     19         <!-- popper.js 不知道有啥用-->
     20         <script src="{% static 'app/js/popper-1.14.7.min.js' %}" ></script>
     21         <script src="{% static 'app/js/bootstrap.min.js' %}"></script>
     22         <script src="{% static 'app/js/bootstrap-table.min.js' %}"></script>
     23         <script src="{% static 'app/js/bootstrap-table-zh-CN.min.js' %}"></script>    
     24         <script src="{% static 'app/js/bootstrap-table-export.min.js' %}"></script>
     25         <script src="{% static 'app/js/tableExport-1.10.19.min.js' %}"></script>
     26         <!-- 图标、字体库 :决定表格右上角的图标是否显示-->
     27         <script src="{% static 'app/js/font-awesome/all.min.js' %}"></script>
     28         <!--<script src="{% static 'app/js/tableExport.js' %}"></script>-->
     29         
     30         <!--admin 相关-->
     31         <link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css" />
     32         <link rel="stylesheet" type="text/css" href="/static/admin/css/responsive.css" />
     33 
     34         <script type="text/javascript" src="/admin/jsi18n/"></script>
     35         <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script>
     36         <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
     37         <script type="text/javascript" src="/static/admin/js/core.js"></script>
     38         <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script>
     39         <script type="text/javascript" src="/static/admin/js/actions.js"></script>
     40         <script type="text/javascript" src="/static/admin/js/urlify.js"></script>
     41         <script type="text/javascript" src="/static/admin/js/prepopulate.js"></script>
     42         <script type="text/javascript" src="/static/admin/js/vendor/xregexp/xregexp.js"></script>
     43         
     44         <!--其他-->
     45         <link href="https://cdn.bootcss.com/highlight.js/9.15.8/styles/github.min.css" rel="stylesheet">
     46         
     47         
     48         <title>All apps</title>
     49     <style>
     50         #mytab  thead{background: #5488c4;font-size:16px;}<!--对表格头部添加样式-->
     51     </style>
     52     </head>
     53 <body>
     54     <div class="container">
     55         <div class="row">
     56             <div class="col-md-8"><h2>...</h2></div>
     57             <div class="col-md-3">{{ user }}</div>
     58             <div class="col-md-1"><a class="btn btn-mini btn-info"href="{% url 'app:logout'%}" >Exit</a></div>
     59             
     60         </div>
     61     </div>
     62     <br><!--换行-->
     63     
     64     
     65     <!--导航栏外框-->
     66     <div class="container-fluid">
     67             <nav class="navbar navbar-expand-md bg-secondary navbar-dark">
     68                 <!--导航栏内容-->
     69                   <div class="container">
     70                       <!--导航列表-->
     71                       <ul class="navbar-nav">
     72                         <li class="nav-item">
     73                           <a class="nav-link " href="{% url 'app:index' %}">Home</a>
     74                         </li>
     75                         <li class="nav-item">
     76                           <a class="nav-link active" href="{% url 'app:apps' %}">Link1</a>
     77                         </li>
     78                         <li class="nav-item">
     79                           <a class="nav-link" href="{% url 'app:apps2' %}">Link2</a>
     80                         </li>
     81                         <li class="nav-item">
     82                           <a class="nav-link" href="{% url 'app:other' %}">Link3</a>
     83                         </li>
     84                         <li class="nav-item">
     85                           <a class="nav-link disabled" href="#">Link 3</a>
     86                         </li>
     87                       </ul>
     88                       <!--搜索表单-->
     89                     <form class="form-inline ">
     90                         <input class="form-control" type="text" placeholder="Search">
     91                         <button class="btn btn-success" type="submit">Search</button>
     92                     </form>    
     93                   </div>
     94             </nav><!--导航结束-->
     95         </div>    <!--导航栏外框结束-->
     96         
     97         
     98         <!--搜索框 start   -->
     99         <!--
    100         <div class="container">
    101             <fieldset>
    102                 <legend>搜索信息</legend>
    103                 <form class="form-inline " action="{% url 'app:apps_search' %}" method="post">
    104                     {% csrf_token %}
    105                     <div style="margin=10px 10px"> 
    106                         <label class="form-control" type="label">平台号</label>
    107                         <input class="form-control" type="text" placeholder="platform_num" name="platform_num">                
    108                         <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    109     
    110                         <label class="form-control" type="label">SVN号</label>
    111                         <input class="form-control" type="text" placeholder="svn" name="svn_num">
    112                         <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    113                     
    114                         <label class="form-control" type="label" for="sel_ternimal">终端类型</label>
    115                         <input class="form-control" type="text" placeholder="terminal" name="terminal">
    116                         <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    117                         <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    118                         <br/><br/>      
    119                        </div>
    120                     
    121                     
    122                     
    123                     <label for="sel_ternimal">测试状态</label>
    124                     <div>
    125                         <select class="form-control" id="test_status" name="test_status">
    126                             <option value ="">请选择</option>
    127                             <option value ="0">测试完毕</option>
    128                             <option value ="1">待测试</option>
    129                             <option value ="2">重发版本</option>
    130                         </select>
    131                     </div>
    132                     <br/>
    133                     <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    134                     
    135                     
    136                     <label for="sel_ternimal">发布至工厂</label>
    137                     <div>
    138                         <select class="form-control" id="pub_to_factory" name="pub_to_factory">
    139                             <option value ="">请选择</option>
    140                             <option value ="0">未发布</option>
    141                             <option value ="1">已发布</option>
    142                         </select>
    143                     </div>
    144                     <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    145                     
    146                     <label for="pub_to_app">发布至接入</label>
    147                     <div>
    148                         <select class="form-control" id="pub_to_app" name="pub_to_app">
    149                             <option value ="">请选择</option>
    150                             <option value ="0">未发布</option>
    151                             <option value ="1">已发布</option>                         
    152                         </select>
    153                     </div>
    154                     <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    155                     <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    156                  
    157                     <div>
    158                         <button class="btn btn-success" type="submit" style="float:right">搜索</button>
    159                     </div>
    160                     
    161                 </form>    
    162             </fieldset>
    163         </div>    -->
    164         <!--搜索框 end-->
    165         <br/>
    166         
    167 <!--提示消息-->
    168 <!--提示消息-->  
    169 <div class="container">  
    170     <div class="my_message">
    171     {% if messages %}
    172         {% for message in messages %}
    173         <div class="alert alert-{{ message.tags }} alert-dismissible" role="alert">
    174         <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
    175                 aria-hidden="true">&times;</span></button>
    176         {{ message }}
    177         </div>
    178         {% endfor %}
    179     {% endif %}
    180     </div>
    181 </div>  
    182 
    183         
    184             
    185         <div class="container"><!--主要内容-->
    186             <div>
    187             <a type="button" class="related-widget-wrapper-link add-related btn btn-primary" id="add_id_app" href="/admin/app/app/add/?_to_field=id&_popup=1" title="新增版本">&nbsp;新增版本 <img src="/static/admin/img/icon-addlink.svg" alt="新增"/></a>
    188             <button type="button" onclick="exportData();" class='btn btn-mini btn-info'>导出数据</button>        
    189             </div>
    190         </div>
    191 
    192         
    193         
    194         <div class="container">
    195         <br/>
    196           <!-- table class="container-fluid" -->
    197             <div id="toolbar">
    198                 <select class="form-control">
    199                     <option value="">Export Basic</option>
    200                     <option value="all">Export All</option>
    201                     <option value="selected">Export Selected</option>
    202                 </select>
    203             </div>
    204 
    205             <table class="table-striped table-bordered table-sm" data-classes="table table-hover " id="mytab" style="font-size:14px;">
    206     <!--
    207       <thead>
    208         <tr>
    209           <th data-field="terminal_name">终端型号</th>
    210           <th data-field="app_name">名称</th>
    211           <th data-field="file_type">文件类型</th>
    212       
    213         </tr>
    214       </thead>-->
    215             </table>    
    216         </div>
    217     <!--主要内容-->
    218     
    219         <br><br><br><br><!--换行-->
    220         <!--页脚-->
    221         <!--页脚-->    
    222         <div class="container-fluid">    
    223             <footer id="site-footer">
    224                 <div class="row">
    225                     <div class="col-md-12">
    226                         <p class="copyright">&copy DC - Test &nbsp;&nbsp;<a href="#"target="_blank" title="">2020</a></p>                                                                      
    227                     </div>
    228                 </div>
    229             </footer>
    230         </div>
    231 
    232 <script>
    233 
    234 $('#toolbar').find('select').change(function () {//显示复选框,不需要的话可以去掉
    235     var $mytab = $('#mytab').bootstrapTable('destroy').bootstrapTable({//显示表格内容及分页
    236     //url: '/app/table_data/',//返回的是{'tatal':total,'rows':rows}根据需要来返回
    237     url:{% url 'app:table_data' %},
    238     method: 'get',
    239     toolbar: "#toolbar",
    240     //contentType:"application/x-www-form-urlencoded; charset=UTF-8",//post请求时需设置
    241     cache: false,
    242     //uniqueId: "ID",
    243     //fixedColumns: true, 
    244     //fixedNumber: -1,//固定列数
    245     //striped: true, // 是否显示行间隔色 无效果
    246     showColumns: true,                  //是否显示列筛选按钮
    247     showRefresh: true,                  //是否显示刷新按钮
    248     showToggle: true,
    249     minimumCountColumns: 2,             //最少允许的列数
    250     clickToSelect: true,               //是否启用点击选中行
    251     dataType: "json",//json数据
    252     undefinedText: '--',
    253     search: false,  //是否显示查询框,没什么用
    254     sortable: true,                     //是否启用排序
    255     sortOrder: "desc",                   //排序方式:asc,desc
    256     sortName: 'submit_date', // 要排序的字段   
    257     
    258     pagination: true,//是否分页
    259     pageNumber: 1,//第几页
    260     pageSize: 5,//每页显示条数
    261     sidePagination: "server",//服务器端分页,没有的话不显示导航页码
    262     pageList: [5, 10, 20, 50, 100, 'all'],
    263     paginationLoop: false,
    264     paginationPreText: "&larr; Previous",
    265     paginationNextText: "Next &rarr;",
    266     queryParamsType: "",//queryParamsType: 'limit',//
    267     queryParams: queryParams,
    268     responseHandler: function (res) {
    269         //如果后台返回的json格式不是{rows:[{...},{...}],total:100},可以在这块处理成这样的格式     
    270       console.info(res);
    271       //console.log('1');
    272       console.log(res.messages);
    273       //'messages':res.messages;//后端返回的非total、rows数据
    274       //$("#invite_month").html(res.month);
    275       data = {                            //return bootstrap-table能处理的数据格式
    276           "total":res.total,
    277           "rows":res.rows,
    278       };
    279     return data;
    280     },
    281     showExport: true,//是否显示导出按钮
    282     buttonsAlign:"right",  //按钮位置
    283     exportDataType: $('#toolbar').find('select').val(),//根据toolbar的值来确定
    284     //exportDataType: "all",              //'basic', 'all', 'selected'.
    285     exportTypes:['excel','xlsx'],        //导出类型
    286     
    287     exportOptions:{
    288                   type: 'excel', 
    289                   //exportDataType: "all",
    290                   escape: 'false',
    291                   //ignoreColumn: [0,-1],          //忽略第1列、最后一列  
    292                   ignoreColumn: [-1],//忽略最后操作列
    293                   //fileName: '版本数据导出',              //文件名称设置  
    294                   fileName: new Date().getTime(),//设置导出的表的默认名称
    295                   worksheetName: 'Sheet1',          //表格工作区名称  
    296                   tableName: 'apps',  
    297                   //excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],  
    298                   //onMsoNumberFormat: DoOnMsoNumberFormat,  
    299                   onMsoNumberFormat: doOnMsoNumberFormat,
    300                   onCellHtmlData: DoOnCellHtmlData,
    301               },
    302     columns: [
    303         {
    304             //field: 'state',
    305             checkbox: true,
    306             visible: $('#toolbar').find('select').val() === 'selected',
    307         },{
    308             field: 'id',
    309             title:'ID',
    310              '5%',//'10%'
    311             sortable:false,
    312             visible:false,
    313             align: 'center',
    314             valign: 'middle',
    315             
    316         },{
    317             field: 'terminal_name',
    318             title:'产品名称',
    319              '3%',
    320             sortable:false,
    321             align: 'center',
    322             valign: 'middle',
    323         },{
    324             field: 'department',
    325             title:'部门',
    326              '2%',
    327             sortable:false,
    328             align: 'center',
    329             valign: 'middle',
    330             
    331         },{
    332             field: 'app_name',
    333             title:'name',
    334              '30%',
    335             align: 'left',
    336             valign: 'middle',
    337             formatter: function(value, row, index){
    338                 res = "<a style='color:blue; white-space:nowrap;' href='/apps/"+row.id+"/' title='点击查看详情'>"+ row.app_name +"</a>"
    339                 return res
    340             },
    341             
    342         },{
    343             field: 'status',
    344             title:'测试状态',
    345              '3%',
    346             sortable:false,
    347             align: 'center',
    348             valign: 'middle',
    349             formatter: function(value, row, index){
    350                 if (value == '待测试'){
    351                     res = "<span style='color:red'>"+ value +"</span>";
    352                 }else if (value == '测试完毕'){
    353                     res = "<span style='color:green'>"+ value +"</span>";
    354                 }else{
    355                     res = value;
    356                 }
    357                 return res;
    358             }
    359         },{
    360             field: 'submit_date',
    361             title:'提测日期',
    362              '5%',
    363             sortable:false ,
    364             align: 'center',
    365             valign: 'middle',
    366             formatter:function(value,row,index){
    367                 res = "<span style='white-space:nowrap;'>"+ value +"</span>";//style='white-space:nowrap;'设置不换行
    368                 return res
    369             }
    370         },{
    371             field: 'submit_programmer',
    372             title:'提测人',
    373              '3%',
    374             sortable:false,
    375             align: 'center',
    376             valign: 'middle',
    377         },{
    378             field: 'valid',
    379             title: '有效',
    380              '1%',
    381             sortable:false,
    382             align: 'center',
    383             valign: 'middle',
    384             //editable:true,//需要导入对应的css、js
    385             formatter: function(value, row, index){
    386                 if (value == ''){
    387                     res = "";
    388                 }else if (value == '0'){
    389                     res = "<span style='color:red'>"+ value +"</span>";
    390                 }else{
    391                     res = value;
    392                 }
    393                 return res;
    394             }
    395         },{
    396             field: 'prospect_testdays',
    397             title:'预估天数',
    398              '2%',
    399             visible:false,
    400             sortable:false,
    401             align: 'center',
    402             valign: 'middle',
    403         },{
    404             field: 'start_time',
    405             title:'开始日期',
    406              '5%',
    407             sortable:false,
    408             visible:false,
    409             align: 'center',
    410             valign: 'middle',
    411             formatter: function(value, row, index){
    412                 if(value == 'None'){
    413                     return "";
    414                 }else{
    415                     res = "<span style='white-space:nowrap;'>"+ value +"</span>";//style='white-space:nowrap;'设置不换行
    416                     return res;
    417                 }
    418             },
    419         },{
    420             field: 'end_time',
    421             title:'结束日期',
    422              '5%',
    423             sortable:false,
    424             visible:false,
    425             align: 'center',
    426             valign: 'middle',
    427             formatter: function(value, row, index){
    428                 if(value == 'None'){
    429                     return "";
    430                 }else{
    431                     res = "<span style='white-space:nowrap;'>"+ value +"</span>";//style='white-space:nowrap;'设置不换行
    432                     return res;
    433                 }
    434             },
    435         },{
    436             field: 'test_type',
    437             title:'测试类型',
    438              '4%',
    439             sortable:false,
    440             visible:false,
    441             align: 'center',
    442             valign: 'middle',
    443         },{
    444             field: 'tester',
    445             title:'测试员',
    446              '2%',
    447             sortable:false,
    448             align: 'center',
    449             valign: 'middle',
    450         },{
    451             field: 'test_report',
    452             title:'测试报告',
    453              '3%',
    454             sortable:false,
    455             visible:false,
    456             align: 'center',
    457             valign: 'middle',
    458         },{
    459             field: 'remark',
    460             title:'备注',
    461              '5%',
    462             sortable:false,
    463             visible:false,
    464             align: 'center',
    465             valign: 'middle',
    466         },{
    467             title:'操 作(查|改|删)',
    468              '20%',
    469             align: 'center',
    470             valign: 'middle',
    471             formatter: actionFormatter,
    472         }
    473     ],        
    474         
    475 });
    476 
    477 }).trigger('change');//根据#toolbar的选择,来显示第一列的复选框
    478 
    479 //查询参数 'limit'
    480 function queryParams_limit(params) {
    481     return {
    482         limit: params.limit,
    483         offset: params.offset,
    484         //nextPage: params.pageNumber,
    485         //typeId : $('#typeId').val(),
    486         //searchName : $('#searchName').val(),
    487         //searchUrl : $('#searchUrl').val(),
    488     };
    489 }
    490 
    491 //传递至view的参数
    492 function queryParams(params) {
    493     var temp = {
    494             'pageSize' : params.pageSize,
    495             'pageNumber' : params.pageNumber,
    496             //'searchText': params.searchText,
    497             'sortName': params.sortName,
    498             'sortOrder': params.sortOrder
    499         };
    500         return temp;
    501 }
    502 //操作栏格式化
    503 function actionFormatter(value, row, index) {
    504             var id = row.id;
    505             var result = "";//style='white-space:nowrap;'
    506             result += "<a style='color:light green;white-space:nowrap;' href='/apps/"+id+"/' title='查看'><img src='/static/admin/img/icon-viewlink.svg'/></a>";
    507             result += "&nbsp&nbsp&nbsp&nbsp"
    508             result += "<a style='color:light blue;white-space:nowrap;' class='related-widget-wrapper-link change-related' id='change_id_app' href='/admin/app/app/" + id +"/change/?_to_field=id&_popup=1' title='编辑'><img src='/static/admin/img/icon-changelink.svg'/></a>";
    509             result += "&nbsp&nbsp&nbsp"
    510             result += "<a style='color:light blue;white-space:nowrap;' class='related-widget-wrapper-link delete-related' id='delete_id_app' href='/admin/app/app/"+ id +"/delete/?_to_field=id&_popup=1' title='删除'><img src='/static/admin/img/icon-deletelink.svg'/></a>";
    511 
    512             return result;
    513         }
    514 //调试用
    515 function EditViewById(id){
    516     console.log(id)
    517 }
    518 //数字
    519 function doOnMsoNumberFormat(cell, row, col){
    520     var result = "";
    521     if (row > 0 && col == 0){
    522       result = "\@";
    523     }
    524     return result;
    525   }
    526   //处理导出内容,这个方法可以自定义某一行、某一列、甚至某个单元格的内容,也就是将其值设置为自己想要的内容
    527   
    528 
    529 
    530 function exportData(){
    531     //导出数据
    532     $('#mytab').tableExport({
    533                              type: 'excel', 
    534                              exportDataType: $('#toolbar').find('select').val(),//根据toolbar的值来确定
    535                              //exportDataType: "all",
    536                              escape: 'false',
    537                              ignoreColumn: [0, -1],  //忽略某一列的索引  
    538                              fileName: 'apps_all',  //文件名称设置  
    539                              worksheetName: 'sheet1',  //表格工作区名称  
    540                              tableName: 'table',
    541                               });
    542     }
    543         
    544           
    545   
    546     // 自定义按钮导出数据
    547     function exportData_debug(){
    548         $('#mytab').tableExport({
    549             type: 'excel',
    550             exportDataType: $('#toolbar').find('select').val(),//根据toolbar的值来确定
    551             //exportDataType: "all",
    552             ignoreColumn: [0,-1],//忽略某一列的索引
    553             fileName: 'debug',//下载文件名称
    554             onCellHtmlData: function (cell, row, col, data){//处理导出内容,自定义某一行、某一列、某个单元格的内容
    555                 console.info(data);
    556                 return data;
    557             },
    558         });
    559     }
    560 </script>
    561    
    562 </body>
    563         
    564 </html>
    url:{% url 'app:table_data' %},返回json格式的数据{rows:[{...},{...}],total:100}
    如果不是需要的json格式,需要做一下处理:
    responseHandler: function (res) {
            //如果后台返回的json格式不是{rows:[{...},{...}],total:100},可以在这块处理成这样的格式     
          console.info(res);
          console.log(res.messages);
          //'messages':res.messages;//后端返回的非total、rows数据
          data = {                            //return bootstrap-table能处理的数据格式
              "total":res.total,
              "rows":res.rows,
          };
        return data;
        },

    分页:

        pagination: true,//是否分页
        pageNumber: 1,//第几页
        pageSize: 5,//每页显示条数
        sidePagination: "server",//去除后解决排序只在当前页生效
        pageList: [5, 10, 20, 50, 100, 'all'],
        paginationLoop: false,
        paginationPreText: "&larr; Previous",
        paginationNextText: "Next &rarr;",
       queryParams: queryParams,

    //传递至view的参数
    function queryParams(params) {
    var temp = {
    'pageSize' : params.pageSize,//设置分页的每页条数
    'pageNumber' : params.pageNumber,//设置当前是第几页
    //'searchText': params.searchText,
    'sortName': params.sortName,
    'sortOrder': params.sortOrder
    };
    return temp;
    }

     

    数据导出:

    目前只能导出当前页,就算到处类设置成"all",也没用,有知道的可以告知下

        showExport: true,//是否显示导出按钮
        buttonsAlign:"right",  //按钮位置
        exportDataType: "all",              //'basic', 'all', 'selected'.
        exportTypes:['excel','xlsx'],        //导出类型    
        exportOptions:{
                      type: 'excel', 
                      //exportDataType: "all",
                      escape: 'false',
                      //ignoreColumn: [0,-1],          //忽略第1列、最后一列  
                      ignoreColumn: [-1],//忽略最后操作列
                      //fileName: '版本数据导出',              //文件名称设置  
                      fileName: new Date().getTime(),//设置导出的表的默认名称
                      worksheetName: 'Sheet1',          //表格工作区名称  
                      tableName: 'apps',  
                      
                  },

    或者通过button绑定export函数来导出:

     1 <button type="button" onclick="exportData();" class='btn btn-mini btn-info'>导出数据</button>
     2 
     3 
     4 function exportData(){
     5     //导出数据
     6     $('#mytab').tableExport({
     7                              type: 'excel', 
     8                              //exportDataType: $('#toolbar').find('select').val(),//根据toolbar的值来确定
     9                              exportDataType: "all",
    10                              escape: 'false',
    11                              ignoreColumn: [0, -1],  //忽略某一列的索引  
    12                              fileName: 'apps_selected',  //文件名称设置  
    13                              worksheetName: 'sheet1',  //表格工作区名称  
    14                              tableName: 'table',
    15                               });
    16     }   

    也可以导出其他格式,需要添加相关的依赖

    view层

     1 @login_required   
     2 def app_data(request):
     3     msg_list = []
     4     username = request.session.get('user', '') # 读取浏览器登录session
     5     per_page_count = 5#设置每页显示10条记录
     6     request.encoding='utf-8'
     7     if request.method == 'GET':
     8         if 'pageSize' in request.GET and request.GET['pageSize']:
     9             per_page_count = int(request.GET['pageSize'])
    10     elif request.method == 'POST':
    11         if 'pageSize' in request.POST and request.POST['pageSize']:
    12             per_page_count = int(request.POST['pageSize'])    
    13      
    14     app_list = app.objects.all().order_by('-submit_date','-id')
    15     app_counts = app.objects.all().count()
    16     paginator = Paginator(app_list, per_page_count)  #生成paginator对象,设置每页显示per_page_count=10条记录
    17     msg_list.append('查找的版本数量为app_counts:'+str(app_counts))
    18     try: # 捕捉前台传过来的数据,传过来不正常的数据都跳到第一页
    19         page = request.GET.get('pageNumber',1) # page = request.GET.get('page',1) #
    20         currentPage_num=int(page)
    21         app_list = paginator.page(page)  #获取当前页码数的记录列表
    22 
    23         # 这可以循环当前页的对象 paginator.page 也可以循环当前页的内容 currentPage.object_list
    24         # for item in currentPage:
    25         #     print(item.name)
    26     
    27         if paginator.num_pages > 10:  # 判断总页数是否大于 10 页
    28             if  currentPage_num -5 < 1:  # 页数小于前5页就显示前10页
    29                 current_range = range(1,11)
    30             elif currentPage_num + 5 > paginator.num_pages:  # 页数大于最后5页就显示最后10页
    31                 current_range = range(paginator.num_pages-9, paginator.num_pages+1)
    32             else: current_range = range(currentPage_num-5, currentPage_num+5)  # 其他范围为-5页到+5页
    33         else:current_range = paginator.page_range  # 小于10页就显示所有页数
    34     
    35     except Exception as e:
    36         currentPage_num = 1 # 随便乱传取第一页
    37         currentPage = paginator.page(currentPage_num) # 随便乱传则取第一页
    38         current_range = range(1, 11)
    39     
    40     total = app.objects.all().count()
    41     rows = []
    42     data = {"total": total, "rows": rows, 'messages': msg_list}
    43     for app in app_list:
    44         rows.append({
    45                 'id': app.id,
    46                 'terminal_name': app.terminal_name,               
    47                 'app_name':app.app_name,
    48                 'status': app.status, #str(datetime.datetime.now())
    49                 'submit_date':str(app.submit_date),
    50                 'tester':app.tester,
    51                 'prospect_testdays':app.prospect_testdays,
    52                 'start_time':str(app.start_time),
    53                 'end_time':str(app.end_time),
    54                 'test_type':app.test_type,
    55                 'test_report':app.test_report,
    56                 'remark':app.remark,
    57                 
    58                 })
    59         
    60     #return HttpResponse(json.dumps(data), content_type="application/json")
    61     return HttpResponse(json.dumps(data, cls=MyEncoder), content_type="application/json")
    62 
    63 
    64 #自定义序列化方法---解决:TypeError: Object of type xxx is not JSON serializable    
    65 class MyEncoder(json.JSONEncoder): 
    66     def default(self, obj): 
    67         if isinstance(obj, app): 
    68             return obj.__str__()
    69         elif isinstance(obj, Tester): 
    70             return obj.__str__()        
    71         elif isinstance(obj, (datetime.datetime, datetime.date)):
    72             return obj.strftime('%Y-%m-%d')
    73          #elif isinstance(obj, date): 
    74             #return obj.__str__()
    75         return json.JSONEncoder.default(self, obj) 

    设置表格某列元素不自动换行

    {
                field: 'submit_date',
                title:'提测日期',
                 '5%',
                sortable:false ,
                align: 'center',
                valign: 'middle',
                formatter:function(value,row,index){
                    res = "<span style='white-space:nowrap;'>"+ value +"</span>";//style='white-space:nowrap;'设置不换行
                    return res
                }
            }
  • 相关阅读:
    java安装jdk时,执行javac出错
    servlet入门
    maven安装出错原因分析
    备份整个schema的数据
    备份db2schema数据
    UltraEdit使用技巧
    获取数据库分组后的最大值
    什么是jsp
    linux 上使用FTP传输文件
    关于opencv进行rtsp取流播放视频特别慢的问题记录
  • 原文地址:https://www.cnblogs.com/yaner2018/p/13153382.html
Copyright © 2020-2023  润新知