exporting mysql query result by clicking on download button in php file

Topics: Developer Forum, Project Management Forum, User Forum
Feb 7, 2014 at 2:31 PM
System info:
phpExcel version 1.7.9
MySQL Server version: 5.5.8
MySQL client version: mysqlnd 5.0.7-dev
MyphpAdmin Version information: 3.4.4

I want to click on a download button and download the query result into excel file.
the action is i click the button Export and it should call the function export2xls and download the file to the local pc, but for some reason it says the function is not defined. and if i remove the function and download the file on page reload the file cannot be opened it says corrupted.
i guess these are the two problems i'm facing, please help.
no forum gives an example on how to download the file on clicking the button.

here is my code:
$query = "SELECT * FROM employees"; //building query
$rows=$db->select($query); //running query

function export2xls(){
require_once 'Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
                ->setTitle("Office 2007 XLSX Report")
                ->setSubject("Office 2007 XLSX Report")
                ->setDescription("Test XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Deposits Report");
$headings = array('First Name','Last Name','Company','Phone','Gender');
    $rowNumber = 1; 
    $col = 'A';

    foreach($headings as $heading) {
$rowNumber = 2;
    foreach($rows as $row) {
        $col = 'A';
        foreach($row as $cell) { 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Report.xlsx"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

<head> <?php include_once('incs/head.php'); ?> </head> <body class="iframed">
<div class="title">Report</div> <br />
<div class="clear"></div> <button id="export" name"export" onclick="export2xls">Export</button>
<br />
<br />
<table > <thead> <tr> <th>First name</th> <th>Last name</th> <th>Company</th> <th>Phone</th> <th>Gender</th> </tr> </thead> <tbody> <?php foreach ($rows as $row){ <tr> <td><?php echo $row['fname']?>.</td> <td><?php echo $row['lname']?></td> <td><?php echo $row['company']?></td> <td><?php echo $row['phone']?></td> <td><?php echo $row['gender']?></td> </tr> <?php $i++; } } ?> </tbody> </table> <br />
<br />