Home > Software engineering >  PHP generated Excel file doesn't open in Microsoft Excel but works with chrome extension for of
PHP generated Excel file doesn't open in Microsoft Excel but works with chrome extension for of

Time:10-27

This code generates an excel file from MySQL in PHP and downloads it. But the issue is that the excel file opens in google chrome's "Office Editing for Docs, Sheets & Slides" extension, but says invalid excel file when I try to open it in Microsoft excel. How to solve this?


    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename='.$fileName);
    
    echo implode("\t", array_values($heading)) . "\n";
    
    while( $row = mysqli_fetch_array($result)) {
            $record=array();
            $record[]=$row["join_date"];
            $record[]=$agents[$row["agent_id"]];
            $record[]=$row["name"];
            $record[]=$row["amount"];
            $record[]=$brokerages[$row["brokerage"]];
            echo implode("\t", array_values($record)) . "\n";
    }

CodePudding user response:

Your posted data is not Excel or CSV. You are sending TSV

Correct content type for your file is "text/tab-separated-values"

See https://github.com/PHPOffice/PhpSpreadsheet/blob/master/samples/Basic/01_Simple_download_xls.php how to make your data downloaded as XLS document.

CodePudding user response:

It's not really an Excel file. It's a TSV file. With the right file extension (.tsv, not .xlsx), Excel can open it too.

  • Related