zoukankan      html  css  js  c++  java
  • Html Table to Excel 的一种实现 (PHP)

    将HTML 前端生成的 table 作为数据源下载

    思路

    1 将 html 脚本 通过form post到后端

    <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">  
        <tr>  
            <td colspan="5" align="center">导出为EXCEL文档</td>  
        </tr>  
        <tr>  
            <td>标题1</td>  
            <td>标题2</td>  
            <td>标题3</td>  
            <td>标题4</td>  
            <td>标题5</td>  
        </tr>  
        <tr>  
            <td>data</td>  
            <td>data</td>  
            <td>data</td>  
            <td>data</td>  
            <td>data</td>  
        </tr>  
    </table>  
    

     html代码 编码后放到一个 form隐藏域

    <form name='dform' method='post' action='excel.php'>
    <input type="hidden" name='datasource' value=""/>
    </form>
    var source=escape("<table id='tableExcel' width='100%' border='1' cellspacing='0' cellpadding='0'><tr><td colspan='5' align='center'>导出为EXCEL文档</td></tr><tr><td>标题1</td><td>标题2</td><td>标题3</td><td>标题4</td><td>标题5</td></tr><tr><td>data</td><td>data</td><td>data</td><td>data</td><td>data</td></tr></table>  ")
    $("datasource").val(source);
    

     页面做点击下载事件 将form提交

    <input type="button" name="button2" value="EXCEL" onclick="document.forms['dform'].submit();return false;"  style="cursor:hand"/>
    

     2 php接住 作为数据源输出 附件

    // 将 前段 抛过来的 html代码 解码

    function phpUnescape($escstr) { preg_match_all("/%u[0-9A-Za-z]{4}|%.{2}|[0-9a-zA-Z.+-_]+/", $escstr, $matches); $ar = &$matches[0]; $c = ""; foreach($ar as $val) { if (substr($val, 0, 1) != "%") { $c .= $val; } elseif (substr($val, 1, 1) != "u") { $x = hexdec(substr($val, 1, 2)); $c .= chr($x); } else { $val = intval(substr($val, 2), 16); if ($val < 0x7F) // 0000-007F { $c .= chr($val); } elseif ($val < 0x800) // 0080-0800 { $c .= chr(0xC0 | ($val / 64)); $c .= chr(0x80 | ($val % 64)); } else // 0800-FFFF { $c .= chr(0xE0 | (($val / 64) / 64)); $c .= chr(0x80 | (($val / 64) % 64)); $c .= chr(0x80 | ($val % 64)); } } } return $c; } $file="test.xls"; if(isset($_POST)&&$_POST["datasource"]){     //将 html写入 excel文件
    $test=$_POST["datasource"]; header("Content-type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=$file"); echo phpUnescape($_POST["downloaddata"]); }

     这样一来 excel.php文件就可以接受任何抛过来的 html 代码(样式可能丢失)

  • 相关阅读:
    [一个64位操作系统的设计与实现] 3.1 Func_GetFATEntry疑惑
    【参考】 实现X86_64架构下的BootLoader(二)文件系统
    LBA和CHS转换(转)
    Grafana 重置admin密码
    linux-source: not found ubuntu执行脚本报错
    Hbase学习
    高并发理解
    Linux下安装Artemis
    SpringInAction 第八章 发送异步消息
    SpringInAction 六七章总结
  • 原文地址:https://www.cnblogs.com/senion/p/2630581.html
Copyright © 2011-2022 走看看