2014-06-04 148 views
8

因爲很難處理不同瀏覽器之間的不同標準,所以我放棄了試圖使用js或jQuery導出html表格。我想知道我是否可以在HTML中將表格發回服務器,並在服務器上生成一個.xls文件供用戶下載。如何使用PHPExcel將html表格導出爲ex​​cel?

現在使用PHPExcel服務器端,我的代碼是這樣的:

$filename = "DownloadReport"; 
$table = $_POST['table']; 

ini_set('zlib.output_compression','Off'); 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
//the folowing two lines make sure it is saved as a xls file 
header('Content-type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment; filename='.$filename); 

$objReader = PHPExcel_IOFactory::createReader('HTML'); 
$objPHPExcel = $objReader->load($table); 

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

exit; 

問題是我不能直接加載HTML表格。我該如何處理?

還有一個問題是,當我在php中設置標題時,單擊按鈕時文件不會下載。其實我可以查看POST響應的Header的所有屬性,以及響應的內容(在FireBug中),這些都是正確的。

+0

輕微相關 - 你很可能有使用http://excelbuilderjs.com/在JS中創建導出。 – Stephen

+1

將$表保存到一個臨時文件,然後從該文件加載 –

+0

http://stackoverflow.com/questions/23562380/phpexcel-create-spreadsheet-from-html-table – Aba

回答

12

要直接將內容放入$objPHPExcel您需要創建工作表,然後逐個單元格設置值,這不是您想要的。

要插入整個HTML表格,你必須從HTMLReader

Writer下面的代碼讀取它將被用來輸出內容到文件

$filename = "DownloadReport"; 
$table = $_POST['table']; 

// save $table inside temporary file that will be deleted later 
$tmpfile = tempnam(sys_get_temp_dir(), 'html'); 
file_put_contents($tmpfile, $table); 

// insert $table into $objPHPExcel's Active Sheet through $excelHTMLReader 
$objPHPExcel  = new PHPExcel(); 
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML'); 
$excelHTMLReader->loadIntoExisting($tmpfile, $objPHPExcel); 
$objPHPExcel->getActiveSheet()->setTitle('any name you want'); // Change sheet's title if you want 

unlink($tmpfile); // delete temporary file because it isn't needed anymore 

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // header for .xlxs file 
header('Content-Disposition: attachment;filename='.$filename); // specify the download file name 
header('Cache-Control: max-age=0'); 

// Creates a writer to output the $objPHPExcel's content 
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 
$writer->save('php://output'); 
exit; 
+0

如何添加另一個html表同一個文件?請幫助我。 – Mahamadali