繁体   English   中英

如何使用PHP脚本导出Excel文件

[英]How to export a excel file using php script

我正在使用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">

问题是这样的:

  1. function excel_file()在加载页面时执行,而不是单击。

  2. 我得到的excel文件,包括整个页面的数据而不是那个垂直数组“ $tabledata ”的数据

您可以在按钮中包含函数的输出。 您不能将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()函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM