简体   繁体   中英

How to export a excel file using php script

I am exporting a excel sheet using php script and my code is

<?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">

Problem is this:

  1. This function excel_file() execute on loading the page not on click.

  2. The excel file which i get, includes the data of whole page not the data of that perticular array " $tabledata "

You include in your button the output of the function. You cannot combine a javascript onclick with a php function.

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. You catch with PHP the $_GET['action'] and call the excel_file() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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