以前生成模板文件,都是在后端放一个文件,前端提供一个链接地址。碰巧看到用DataTable来生成模板文件的方式,特此记录下。
原理:创建一个空数据的DataTable,提供导出按钮功能,并隐藏DataTable。页面上就只会显示一个按钮,不显示DataTable.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet" /> <link href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" /> </head> <body> <div> <table id="demo" class="display w-100"></table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script> <script> var columnDefsValue = [ { targets: 0, title: "column1", className: "text-center", }, { targets: 1, title: "column2", className: "text-center", }, { targets: 2, title: "column3", className: "text-center", }, { targets: 3, title: "column4", className: "text-center", }, { targets: 4, title: "column5", className: "text-center", } ]; var columnsExport = [0, 1, 2, 3, 4]; var oTable = $('#demo').dataTable({ data: [], "searching": false, dom: 'Bfrtip', buttons: { buttons: [ { extend: "excel", className: 'btn btn-primary', text: " <span class='color-white'>Template</span>", filename: "Template", title: '', exportOptions: { columns: columnsExport }, }, ], dom: { button: { className: 'btn' } } }, info: false, lengthChange: false, cellspacing: true, destroy: true, paging: false, columns: columnDefsValue }); oTable.hide(); </script> </body> </html>
标签:Jquery,center,title,text,targets,className,DataTable,模板 From: https://www.cnblogs.com/WikiChen/p/17351956.html