MTA MTA - 5 months ago 43
PHP Question

PHP create xls from array

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

Please try : As per oficial documentation, you need first 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');
?>