user3607000
user3607000

Reputation: 17

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"

Upvotes: 1

Views: 6087

Answers (1)

Stefan
Stefan

Reputation: 1258

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.

Upvotes: 2

Related Questions