1

I am using PHPExcel 1.8.0 in my project. When I want to generate and download a .xls file with some data from my database, the file is downloaded with garbage data. Here is my code:

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

I have used both ob_end_clean() and ob_clean() but nothing works.

  • Send all headings (as shown in `01simple-download-xls.php`), make sure that there is absolutely nothing being output else where in your code before or after the save – Mark Baker Sep 30 '15 at 07:16
  • 1
    Open the file in a text editor and look for any leading/trailing whitespace, any BOM marker (make sure your script is saved without a BOM header), or any plaintext error messages – Mark Baker Sep 30 '15 at 07:17

1 Answers1

3

Try this code:

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
$objWriter->save('php://output');
Tristan
  • 3,301
  • 8
  • 22
  • 27