PHP create xls from array

YosiFZ picture YosiFZ · Apr 28, 2014 · Viewed 38.6k times · Source

I try to create xls file from array and download it with the browser with this code:

$sheet = array(
    array(
      'a1 data',
      'b1 data',
      'c1 data',
      'd1 data',
    )
  );

  $doc = new PHPExcel();
  $doc->getActiveSheet()->fromArray($sheet, null, 'A1');

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

  // Do your stuff here

  $writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');

The problem is that i get a empty file.Any idea what can be the issue?

Answer

Paul Bele picture Paul Bele · Apr 28, 2014

Please try : As per official documentation, you first need to save the file with the object writer

Please let me know if this is what you wanted

<?php
date_default_timezone_set('America/Los_Angeles');

require_once('PHPExcel.php');

$sheet = array(
    array(
      'a1 data',
      'b1 data',
      'c1 data',
      'd1 data',
    )
  );

  $doc = new PHPExcel();
  $doc->setActiveSheetIndex(0);

  $doc->getActiveSheet()->fromArray($sheet, null, 'A1');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

  // Do your stuff here
  $writer = PHPExcel_IOFactory::createWriter($doc, 'Excel5');

$writer->save('php://output');
?>