如何使用php脚本导出一个excel文件
我正在使用PHP脚本导出一个Excel工作表,我的代码是
<?php function excel_file(){ header("Content-Disposition: attachment; filename=\"demo.xls\""); header("Content-Type: application/vnd.ms-excel;"); header("Pragma: no-cache"); header("Expires: 0"); $out = fopen("php://output", "w"); foreach ($tabledata as $data) { fputcsv($out, $data,"\t"); } fclose($out); } ?>
HTML
<input type="button" name="excel_file" onclick="<?php excel_file(); ?>" value="Download File">
问题是这样的:
-
这个
function excel_file()
在加载页面时不执行就点击执行。 -
我得到的excel文件,包含整个页面的数据而不是该数组的数据“
$tabledata
”
你在你的button中包含了函数的输出。 你不能将一个javascript onclick和一个php函数结合起来。
HTML:
<a href="your_url.php?action=xls">Excel</a>
然后在你的代码中
if(isset($_GET['action']) && $_GET['action'] == 'xls') { excel_file(); exit; }
通过这种方式,您可以单击Excel链接并将该操作发送到服务器。 你用PHP捕获$_GET['action']
并调用excel_file()
函数。