0

I've got a web page that displays data in a table and what I want to add is a button that the user can click to download the table as an Excel file. I use PHPExcel to make the Excel file, and it seems to work with no errors until I actually get to downloading the file - it seems the browser generates the file just fine, but doesn't actually download the finished file.

I did take a look at this question here: phpexcel to download, but I tried what the answers said to do and it didn't seem to change anything.

Here's my frontend code ("table.php"):

<script>
$("#export-to-excel").click(function() {
            $.ajax({
                type: "GET",
                url: "table_create_excel.php",
                data: {
                    action: "exportToExcel",
                    tableRows: rows
                }
            });
}
</script>
<img src='excel-icon.png' id="export-to-excel"/>

Here's my backend code ("table_create_excel.php"):

    require_once "PHPExcel.php";
    $objPHPExcel = new PHPExcel();
    // ...
    // ... generate the excel document from the given data ...
    // ...
    $objPHPExcel->setActiveSheetIndex(0);
    
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Table_Summary.xlsx"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');

Is there something I'm missing that, if I could put it in, would get my browser to download the file? Could the trouble be because I'm making an AJAX call rather than linking to the PHP page directly? Thanks.

  • Does this answer your question? [phpexcel to download](https://stackoverflow.com/questions/8566196/phpexcel-to-download) – Petr Hejda May 11 '21 at 21:57
  • @PetrHejda It doesn't. I tried using the answer from that linked question but it did not seem to change anything. – Walt Gottlieb May 11 '21 at 22:03

1 Answers1

1

Turns out my suspicion was correct, and that you can't use AJAX to download a file. What I did was got rid of the JQuery "click" event and replaced it with an anchor tag around the "export to Excel" icon, which had a link to the PHP file that generated and downloaded the Excel file along with enough parameters to allow the PHP code to re-query the database and rebuild the table that I wanted to export rather than including the table in the data that was sent.