- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- <script src="http://code.jquery.com/jquery-latest.js"></script>
- </head>
- <body>
- <table>
- <thead>
- <th > 姓名 </th>
- <th > 性别 </th>
- <th > 年龄 </th>
- </thead>
- <tbody>
- <tr class="hover-bg">
- <td>aaaa</td>
- <td > 女 </td>
- <td>18</td>
- </tr>
- </tbody>
- </table>
- <a class="download_file" onclick="exportFile()" download="用户列表"> 导出 </a>
- <script>
- function exportFile() {
- var dataArr = [];// 定义数组用来保存所勾选的列表当前行数据
- // 定义表头
- var str = '<tr><th > 姓名 </th><th > 性别提交时间 </th><th > 年龄 </th></tr>'
- // 遍历列表中所购选中的行
- $('table').find('tr.hover-bg').each(function () {
- var Data = new Object();
- Data.AreaName = $(this).find('td:eq(0)').html();
- Data.DataID = $(this).find('td:eq(1)').html();
- Data.EntryTime = $(this).find('td:eq(2)').html();
- dataArr.push(Data);
- })
- if ($('table').find('tr').hasClass('hover-bg')) {
- // 循环遍历, 每行加入 tr 标签, 每个单元格加 td 标签
- for (let i = 0; i <dataArr.length; i++) {
- str += '<tr>';
- for (let item in dataArr[i]) {
- // 增加 \ t 为了不让表格显示科学计数法或者其他格式
- str += `<td>${dataArr[i][item] + '\t'}</td>`;
- }
- str += '</tr>';
- }
- var template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
- xmlns:x="urn:schemas-microsoft-com:office:excel"
- xmlns="http://www.w3.org/TR/REC-html40">
- <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
- <x:Name>'录入列表. xls'</x:Name>
- <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
- </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
- </head><body><table>${str}</table></body></html>`;
- // 实例化一个 Blob 对象, 其构造函数的第一个参数是包含文件内容的数组, 第二个参数是包含文件类型属性的对象
- var blob = new Blob([template], { type: "application/vnd.ms-excel" });
- $('.download_file').attr('href', URL.createObjectURL(blob));
- }
- }
- </script>
- </body>
- </html>
来源: http://www.qdfuns.com/article/50506/dd04181d62ed5336aee96fd7fb98089c.html