How to generate an .xlsx using php

angel enanod picture angel enanod · Jun 22, 2016 · Viewed 80.7k times · Source

I need to generate an Excel file with extension .xlsx.

Here is my simple code:

 $file = "test.xlsx";
 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
 header('Content-Disposition: attachment; filename='.$file);
 $content = "Col1\tCol2\tCol3\t\n";
 $content .= "test1\ttest1\ttest3\t\n";
 $content .= "testtest1\ttesttest2\ttesttest3\t\n";
 echo $content;

But I get this error when I open the generated file:

Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid.

Any ideas?

Answer

Sergey Shuchkin picture Sergey Shuchkin · May 19, 2020

SimpleXLSXGen

$books = [
    ['ISBN', 'title', 'author', 'publisher', 'ctry' ],
    [618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'],
    [908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
];
$xlsx = SimpleXLSXGen::fromArray( $books );
$xlsx->saveAs('books.xlsx');
//  $xlsx->downloadAs('books.xlsx');