2010-06-28 97 views
0

我已經編寫了用於從數據庫獲取數據並將其存儲在Excel工作表中的代碼。我只想下載excel文件。但下面的代碼將PHP文件輸出作爲我的excel文件內容。但我需要下載在PHP文件中創建的Excel文件。如何從PHP代碼下載Excel工作表

<?php 
$start_date="01/06/2010"; 
      $end_date="23/06/2010"; 
      $filename=$user.".xls"; 

      require 'DB.php' ; 
      include 'Spreadsheet/Excel/Writer.php'; 
      $excel = new Spreadsheet_Excel_Writer($filename); 
      $format_bold =& $excel->addFormat(); 
      $format_bold->setBold(); 
      $format_bold->setColor('red'); 
      $sheet= $excel->addWorksheet('Class I'); 
      $sheet->write(0, 0, "Field Name",$format_bold); 
      $sheet->write(0, 1,"Field Name", $format_bold); 
      $sheet->write(0, 2, "Filed Name",$format_bold); 
      $sheet->write(0, 3,"Filed name", $format_bold); 
      $db = DB::connect(connect query); 
      $q=$db->getAll("select * from table_name"); 
      $rowCount=1; 
     foreach ($q as $row) 
     { 
       foreach ($row as $key => $value) 
       { 
        $sheet->write($rowCount, $key, $value); 
       } 
     $rowCount++; 
     } 
header('Pragma: no-cache'); 
header('Expires: 0'); 
header("Content-type: application/x-msexcel"); 
header("Content-Type: application/force-download"); 
header('Content-Disposition: attachment; filename="'$filename'"'); 
?> 

回答

1

您需要添加一個調用send()方法來生成內容。這樣你也不需要任何頭文件,因爲方法會爲你生成它們。

$excel->send($filename); 
0
header ("Expires: Mon, 1 Apr 1974 05:00:00 GMT"); 
header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT"); 
header ("Cache-Control: no-cache, must-revalidate"); 
header ("Pragma: no-cache"); 
header ("Content-type: application/x-msexcel"); 
header ('Content-Disposition: attachment; filename="'.$filename.'"'); 
header ("Content-Description: PHP Generated XLS Data"); 
print $sheet; 

error_reporting();切換到最大拉特?

+0

您的代碼無法正常工作。 – muruga 2010-06-28 11:19:04