简体   繁体   English

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

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

I am exporting a excel sheet using php script and my code is 我正在使用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 HTML

<input type="button" name="excel_file" onclick="<?php excel_file(); ?>" value="Download File">

Problem is this: 问题是这样的:

  1. This function excel_file() execute on loading the page not on click. function excel_file()在加载页面时执行,而不是单击。

  2. The excel file which i get, includes the data of whole page not the data of that perticular array " $tabledata " 我得到的excel文件,包括整个页面的数据而不是那个垂直数组“ $tabledata ”的数据

You include in your button the output of the function. 您可以在按钮中包含函数的输出。 You cannot combine a javascript onclick with a php function. 您不能将javascript onclick与php函数结合使用。

HTML: HTML:

<a href="your_url.php?action=xls">Excel</a>

Then in your code 然后在你的代码中

if(isset($_GET['action']) && $_GET['action'] == 'xls')
{
  excel_file();
  exit;
}

In this way you click on the Excel link and send that action to the server. 这样,您可以单击Excel链接并将该操作发送到服务器。 You catch with PHP the $_GET['action'] and call the excel_file() function. 使用PHP捕获$_GET['action']并调用excel_file()函数。

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

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