Search code examples
phpcodeigniterexport-to-excel

How to export excel in PHP and compatible for all devices


I am trying to export an export file in PHP. I am using Codeigniter Framework.

I exported Excel in this way:

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename={$filename}.xls"); 

It is showing data in Windows in right format. But prompt a message when I initially open it. But When I open it in MAC OS, it is not working.

How can I export Excel in right format that works in Google Drive as well? I have tried so many ways as above and as follows. All not working properly in Mac and Google Drive spreadsheets:

header('Content-Disposition: attachment; filename='.$filename.'.xlsx');
header('Content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 

header('Content-Disposition: attachment; filename='.$filename.'.xls');
header('Content-type: application/vnd.ms-excel'); 

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  

Solution

  • Even though you're using codeigniter I would advise you to load a external library to handle your excel stuff.

    There's library that everyone uses with PHP called phpspreadsheet.

    https://phpspreadsheet.readthedocs.io/en/latest/

    This will handle all the problems you're having and more. It's really easy to install since its available as a composer package.

    https://packagist.org/packages/phpoffice/phpspreadsheet

    Creating a excel file would be as simple as:

    <?php
    
    require 'vendor/autoload.php';
    
    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
    
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', 'Hello World !');
    
    $writer = new Xlsx($spreadsheet);
    $writer->save('hello world.xlsx');
    

    And since your using codeigniter you can combine this with the CI download helper to force download the document.