Abdul Rafay
Abdul Rafay

Reputation: 29

PHP generated Excel file doesn't open in Microsoft Excel but works with chrome extension for office files

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";
    }

Upvotes: 1

Views: 756

Answers (2)

Cybervitexus
Cybervitexus

Reputation: 312

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.

Upvotes: 3

CherryDT
CherryDT

Reputation: 29012

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.

Upvotes: 2

Related Questions