zoukankan      html  css  js  c++  java
  • 使用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>' ?>
  • 相关阅读:
    timestamp的两个属性:CURRENT_TIMESTAMP 和ON UPDATE CURRENT_TIMESTAMP
    python 典型文件结构
    PHP接口开发加密技术实例原理与例子
    一个高效的敏感词过滤方法(PHP)
    Thinkphp自动验证规则
    PHP解析xml文件时报错:I/O warning : failed to load external entity
    访问php网站报500错误时显示错误显示
    15个最受欢迎的Python开源框架
    分布式监控系统开发【day38】:报警策略设计(二)
    分布式监控系统开发【day38】:报警阈值程序逻辑解析(三)
  • 原文地址:https://www.cnblogs.com/NTWang/p/7399449.html
Copyright © 2011-2022 走看看