Hi there,

I have trouble opening a xlsx fomatted files using Excel 2007 and Excel 2010 when I try to open it through PHP.
The warning goes as-
"Excel found unreadable content in report.xlsx. Do you want to recover the contents of this workbook?If you trust the source of this workbook, click Yes".

opening this file directly by double clicking on it has no Issues.
But I need to open it via php.
I've set content types as below, and the error occurs at that point:

header("Content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition:attachment;filename=report.xlsx");
readfile("C:\wamp\www\proj\includes\out\fileone.xlsx");

Do I have a wrong Content type?or what could be the issue? Is this related to apache?
You help is very much appreciated and thanks in advance.

    I fixed this issue. Though I'm not sure if it's the best way, the warning messages on Excel2007/2010 are gone and the files open perfectly fine.

    I added some more headers and an important one was
    header("Content-Length: ".filesize($filename)); //in this case $filename = fileone.xlsx
    Then I used flush() before the file read . (IM)

    The following links could be useful:

    http://stackoverflow.com/questions/2274780/download-xlsx-file-using-response-transmitfile

    http://stackoverflow.com/questions/5842254/excel-and-unreadable-content-when-creating-an-open-xml-spreadsheet-with-memory?answertab=active#tab-top

    fixed code:

    $filename = 'C:\wamp\www\proj\includes\out\fileone.xlsx';
    $filename = realpath($filename);
    $len = filesize($filename);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: application/openxmlformats-officedocument.spreadsheetml.sheet");
    header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$len);
    flush();
    set_time_limit(0);
    readfile("$filename") or die("File not found.");

    Hope someone will find this helpful. Please post if there's a better way of overcoming this issue.

    Regards,
    Nish 🙂

      Write a Reply...