0

I would like to know how to redirect the page after creating a file using PHPExcel. File created is ok but redirection to another page is not. Below are some codes.

$excel -> setActiveSheetIndex(0);
$_SESSION["information"] = "Motor Line Checking Completed.";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename='".$report_name.".xlsx'");
header("Cache-Control: max-age=0");
$writer = PHPExcel_IOFactory::createWriter($excel, "Excel2007");
$writer -> save('php://output');
exit;
header("Location: ".$_SERVER["HTTP_HOST"]."/../../");
exit;

NOTES:

  • If I remove exit;after save();, xlsx file will be corrupted.
  • If I move header("Location:...");before save();, it will redirect but will not create xlsx.
  • I also tried redirecting using javascript.

What I want is to create xlsx and redirect the page after.

pnuts
  • 58,317
  • 11
  • 87
  • 139
juntapao
  • 407
  • 3
  • 12

1 Answers1

0

I came up with a solution to just provide a link on the redirected page. From that page I can create trigger for that link to just automatically download the file.

From the page that creates the file:

$writer = PHPExcel_IOFactory::createWriter($excel, "Excel2007");
$metaDatas = stream_get_meta_data(tmpfile());
$tmpFilename = $metaDatas['uri'];
$writer -> save($tmpFilename);
$newfile = "../outbox/".$report_name."_".substr(date("Y"), -2).date("mdhis").".xlsx";
rename($tmpFilename, $newfile);
$tmpary = explode("/", $newfile);
$_SESSION["download"] = $tmpary[count($tmpary) - 1];
$_SESSION["information"] = "File Creation Completed.";

From redirected page:

<?php
if(isset($_SESSION["information"])) {
    echo $_SESSION["information"];
    if(isset($_SESSION["download"])) {
?>
    <a href="outbox/<?php echo $_SESSION["download"]; ?>">
        <button class="download" type="button">Click here to download <?php echo $_SESSION["download"]; ?> file.</button>
    </a>
<?php
    }
    session_unset();
}
?>
juntapao
  • 407
  • 3
  • 12
  • I am facing same problem, but `session` method not going to work. But my code looks like [stackoverflow question Link](http://stackoverflow.com/questions/31593588/create-formatted-excel-spreadsheet-with-mysql-data-and-php-using-tables/31594131#31594131) Do you got me? – saleem ahmed Jan 10 '16 at 03:34
  • Do you have `session_start()` at the beginning of the page? – juntapao Jan 13 '16 at 03:41
  • I have followed another method – saleem ahmed Jan 13 '16 at 05:32