把table表格的內容導出成excel 或者word等格式(簡單容易不需要太多php)
導出需注意
1. 樣式都在行間,導出excel表格會繼承樣式包括colspan、rowspan,非表格元素,樣式不會生效
2.樣式非行間,導出excel之后,只有數據,不保存樣式。excel不支持非表格元素的樣式
原理
JS:獲取表格的dom結構內容,賦值給表單,提交表單
PHP:設置請求頭,獲取請求的表格內容,echo輸出,由於獲取的表格沒有table標簽,輸出的時候要加上,如果獲取的時候有,就不需要了
注意:需要在服務器模式下運行
html+js
<!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="jquery.min.js"></script> <style media="screen"> table{ border-collapse:collapse; border-spacing:0; } </style> </head> <body> <button type="button" name="button" id="export">導出</button> <table id="tablelist" border="1" > <tr> <th rowspan="2">11111</th> <td>11111</td> <td>11111</td> </tr> <tr> <td>22222</td> <td>22222</td> </tr> </table> <form action="./excel.php" method="post" id="excelfromtable" style="" target="_blank"> <input name="excelContent" id="excelContent" type="hidden" value="" autocomplete="off"/> </form> <script type="text/javascript"> $(function(){ $('#export').click(function(){ var excelContent = $('#tablelist').html(); //獲取表格內容 $('input[name=excelContent]').val(excelContent);//賦值給表單 $('#excelfromtable').submit();//表單提交,提交到php }) }) </script> </body> </html>
php
<?php echo '<meta http-equiv="Content-type" content="text/html; charset=utf-8 " />'; //設置內容,編碼 header('Content-type:application/vnd.ms-excel');//設置請求頭類型 header('Content-Disposition:filename=PreSortiong.xls');//設置導出格式 可以改 PreSortiong.xls 后綴成相應的格式
$content = $_POST['excelContent'];//獲取表格內容 echo '<table cellpadding="1" cellspacing="1" id="" border="1" bgcolor="red">'; echo $content ; echo '</table>' ?>