Phpexcel xls文件在下载时显示垃圾数据

时间:2015-09-30 07:09:18

标签: php download phpexcel xls

我在我的项目中使用PHPExcel 1.8.0。当我想使用我的数据库中的一些数据生成和下载.xls文件时,将使用垃圾数据下载该文件。这是我的代码:

$result = mysql_query("select * from my_table");
ob_start();

  //excel code
  $this->load->library('excel');

//activate worksheet number 1
        $this->excel->setActiveSheetIndex(0);
//name the worksheet
    $this->excel->getActiveSheet()->setTitle('test worksheet');

    $rowNumber = 5;
    while ($row = mysql_fetch_assoc($result)) {
      $col = 'B';
        foreach ($fields as $cell) {
            $this->excel->getActiveSheet()->setCellValue($col .$rowNumber, $row[$cell]);
            $col++;
        }

        $rowNumber++;
    }
       // ob_end_clean();
    //  ob_clean() ;    

    $filename='report.xls'; //save our workbook as this file name
    header('Content-Type: application/vnd.ms-excel'); //mime type

   header('Content-Disposition: attachment;filename="'.$filename.'"'); 
    header('Cache-Control: max-age=0'); //no cache

    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
  exit(); 

我已经使用了ob_end_clean()和ob_clean(),但没有任何效果。

1 个答案:

答案 0 :(得分:1)

试试这段代码:

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