Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP create xls from array

Tags:

php

xls

phpexcel

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?

like image 427
YosiFZ Avatar asked Apr 28 '14 18:04

YosiFZ


1 Answers

Sometimes we just can't use an external library/class like PHPExcel, in this case, I recommend you to use HTML table and change headers as xls, you can create it easily from array, very simple example:

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

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

$table = '<table><tbody><tr><td>A1</td><td>B1</td><td>C1</td><td>D1</td></tr>';
foreach ($sheet as $row) {
    $table.= '<tr><td>'.  implode('</td><td>', $row) . '</td></tr>';
}
$table.= '</tbody></table>';

header('Content-Encoding: UTF-8');
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header ("Content-type: application/x-msexcel;charset=UTF-8");
header ("Content-Disposition: attachment; filename=productsExport.xls" );

echo $table;
?>
like image 97
Paulo Victor Avatar answered Oct 05 '22 20:10

Paulo Victor