Jesse Green
Jesse Green

Reputation: 373

PHP Excel file format doesn't match extension

I'm getting the above error (Windows only) on XLS files I'm exporting with my PHPExcel Script. Most of the reference I've seen to this error involves trailing/leading spaces/newlines when outputting to php://output (PHPExcel generated excel file not working. (File format or extension is invalid ). I'm not outputting in that fashion however. Instead I'm outputting the XLS file to a file path on my server and then passing a URL back to the browser to download. I've checked my PHP script and the file that it created for spaces and newlines at the beginning or end and there are none. Here's the section of my code that generates the PHP code.

$xls = new PHPExcel();
$xls->getActiveSheet()->setTitle(substr($reportName, 0, 31));
$xls->setActiveSheetIndex(0);
//iterate over the headers
foreach($headers as $i => $header){
    $xls->getActiveSheet()->SetCellValue(getExcelColumn($i+1) . '1', $header);
}
//iterate over the table contents
foreach($tableContents as $rowNum => $row) {
    foreach($row as $col => $cell) {
        if(strpos($cell, "none specified") > -1)
            $cell = "N/A";
        $cell = explode("<br />", $cell);
        $cell = implode(", ", $cell);
        $xls->getActiveSheet()->SetCellValue(getExcelColumn($col+1) . ($rowNum+2), $cell);
    }
}
$fileName = createRandomKey(20) . '-' . $reportName . '.xls';
$w = new PHPExcel_Writer_Excel2007($xls);
$w->save("savedExports/$fileName");

$headers and $tableContents are taken from $_POST data and there's a few helper functions called in this code.

Upvotes: 2

Views: 4234

Answers (1)

Alessandro Lai
Alessandro Lai

Reputation: 2274

You should do:

$fileName = createRandomKey(20) . '-' . $reportName . '.xlsx';

*.xlsx is the right extension for Excel 2007 files

Also:

strpos can return false, you should do

strpos($cell, "none specified") !== false

Upvotes: 3

Related Questions