2014-09-12 83 views
0

好的,現在我看了phpexcel的例子。據我所知,頁面上不應該有任何其他輸出,以便製作正確的xls文件。我是這麼認爲的,因爲當我有PHPexcel問題

echo "some output and my form for query"; 
      $objPHPExcel = new PHPExcel(); 
      $objPHPExcel->getProperties()->setCreator("Administrator"); 
      $objPHPExcel->getProperties()->setLastModifiedBy("Administrator"); 
      $objPHPExcel->getProperties()->setTitle("test"); 
      $objPHPExcel->getProperties()->setSubject("test"); 
      $objPHPExcel->getProperties()->setDescription("test"); 

      $objPHPExcel->setActiveSheetIndex(0); 
      $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello'); 
      $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!'); 
      $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello'); 
      $objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!'); 

      $objPHPExcel->getActiveSheet()->setTitle('Simple'); 

      $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
      // Redirect output to a client’s web browser (Excel5) 
      header('Content-Type: application/vnd.ms-excel'); 
      header('Content-Disposition: attachment;filename="01simple.xls"'); 
      header('Cache-Control: max-age=0'); 
      // If you're serving to IE 9, then the following may be needed 
      header('Cache-Control: max-age=1'); 

      // If you're serving to IE over SSL, then the following may be needed 
      header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past 
      header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified 
      header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 
      header ('Pragma: public'); // HTTP/1.0 
echo"some other code"; 

並得到XLS,它有它doen't必須有CSS鏈接的警告,而且它把大量的文字,除了世界,你好!如在Excel文件鏈接。 它看起來像這樣: Output in excel

我可以把所有工作,XLS其他PHP文件,並與阿賈克斯得到它,但我怎麼給查詢的結果,以這個文件?所有的查詢應該在我的主文件中,因爲我不想有多個連接到數據庫。如何清楚,我想要什麼。任何建議?

+1

你說得對,你不能有呼應的輸出,併發送一個Excel文件一個瀏覽器下載相同的請求,否則你只是破壞Excel格式文件,以便MS Excel不能正確讀取它。您在單個請求中生成___either__ HTML標記,___或者Excel文件,但不能同時生成....這不是PHPExcel問題,它是一個http問題....如果您有請求生成圖像文件或pdf或數據的zip存檔....每個請求只有一個文件類型 – 2014-09-12 17:04:19

+0

感謝您的解釋。任何想法如何解決問題? – 2014-09-12 17:10:32

+0

解決方案是隻發送一個響應類型與每個請求....即使這意味着每個請求必須從數據庫中讀取數據 – 2014-09-12 17:13:54

回答

0

要下載xls(x)文件,您必須設置正確的標題並清理緩衝區以避免錯誤的流。 作爲文檔解釋了你可以用這個代碼嘗試:

//------------- Enter your code before this line --------- // 

// Cleaning buffer 
ob_clean(); 

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

/* Or you can use 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); 
*/ 

// redirect output to client browser 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="your_filename.xls"'); 
/* Use this for Writer Excel2007  
header('Content-Disposition: attachment;filename="your_filename.xlsx"'); 
*/ 
header('Cache-Control: max-age=0'); 

//Start Download 
$objWriter->save('php://output'); 

您可以參考here爲PHPExcel的開發者文檔