Ashwin
Ashwin

Reputation: 460

Get corrupted xls file while downloading it using PHPExcel

In my current project, I used PHPExcel 1.7.8 for exporting data into excel. As per suggested I successfully configured it in my project and successfully generate xls file and stored it but when I tried to download xls file then I gor corrupted xls file without getting any error message. I have following code for the same.

/** Error reporting */
if (PHP_SAPI == 'cli')
     die('This example should only be run from a Web Browser');

/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
      ->setLastModifiedBy("Maarten Balliauw")
      ->setTitle("PHPExcel Test Document")
      ->setSubject("PHPExcel Test Document")
      ->setDescription("Test document for PHPExcel, generated using PHP classes.")
      ->setKeywords("office PHPExcel php")
      ->setCategory("Test result file");

// Add some data
$objPHPExcel->setActiveSheetIndex(0)
         ->setCellValue('A1', 'Hello')
         ->setCellValue('B1', 'world!')
         ->setCellValue('C1', 'Hello')
         ->setCellValue('D1', 'world!');

// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A2', 'Miscellaneous glyphs')
            ->setCellValue('B2', 'This is test text by me');

// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Redirect output to a client’s web browser (Excel5)
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");

// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save(str_replace('.php', '.xls', __FILE__));
$objWriter->save("php://output");
exit;

Thank you.

Upvotes: 4

Views: 7926

Answers (1)

leonard.javiniar
leonard.javiniar

Reputation: 555

Can you try this? Just before your

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"filename.xls\"");
header("Cache-Control: max-age=0");

put ob_end_clean();.

There might be something wrong about your output buffer.

Upvotes: 3

Related Questions