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" οnclick="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 代码(样式可能丢失)

转载于:https://www.cnblogs.com/senion/archive/2012/08/09/2630581.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值