使用JS和PHP导出table表格

把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>' ?>

 

posted @ 2017-08-20 11:53  NT.Wang  阅读(2444)  评论(0编辑  收藏  举报