使用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>' ?>

 

转载于:https://www.cnblogs.com/NTWang/p/7399449.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值