2015-04-20 30 views
0

我想知道如何使用PHPExcel創建文件後重定向頁面。創建的文件沒問題,但重定向到另一個頁面不是。以下是一些代碼。創建Excel文件後PHPExcel重定向頁面

$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; 

注:

  • 如果我刪除exit;save();後,XLSX文件將被損壞。
  • 如果我在save();之前移動header("Location:...");,它將重定向但不會創建xlsx。
  • 我也嘗試使用JavaScript重定向。

我想要的是創建xlsx並重定向頁面後。

+2

可以讓這個excel文件重定向頁面後。 –

+1

在這裏看到一個參考:http://stackoverflow.com/questions/822707/php-generate-file-for-download-then-redirect – nomistic

+0

嗨@AnowarCst,這是否意味着我必須先重定向並在那裏創建文件? – juntapao

回答

0

我想出了一個解決方案,只提供重定向頁面上的鏈接。從該頁面我可以創建該鏈接的觸發器來自動下載文件。

從創建該文件的頁面:

$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."; 

從重定向頁面:

<?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(); 
} 
?> 
+0

我面臨同樣的問題,但會話方法不起作用。但我的代碼看起來像[stackoverflow問題鏈接](http://stackoverflow.com/questions/31593588/create-formatted-excel-spreadsheet-with-mysql-data-and-php-using-tables/31594131#31594131) 你有我嗎? –

+0

你在頁面的開頭有'session_start()'嗎? – juntapao

+0

我採用了另一種方法 –