PHPExcel creates ‘unreadable content’

PHPphpexcel

I've tried to fix this problem about 1000 different ways. Appreciate if anyone else can spot the problem.

I have code using PHPExcel that generates multiple Excel sheets and saves them to disk.

When opening everything from the second file onwards using MS Excel 2010, I get the error "Excel found unreadable content in FILENAME. Do you want to recover the contents of this workbook." The file is 'recovered' and works perfectly ok. Opening in OPen Office does not produce any errors.

Here's a simplified version of the code.

<?php
$filenames = array("filenames go here");

$sheet1 = PHPExcel_IOFactory::load($template1);
$writer1 = new PHPExcel_Writer_Excel2007($sheet1);
$writer1->save('somefilename.xlsx');
//This file opens without problem
$sheet1->disconnectWorksheets();
unset($sheet1);
unset($writer1);

$i = 0;
foreach($filenames as $file){
    $template = "template2.xlsx";
    $fileName = 'filename' . $i . ' .xlsx';
    $spreadsheet = PHPExcel_IOFactory::load($template);
    $objWriter = new PHPExcel_Writer_Excel2007($spreadsheet);
    $objWriter->save($fileName);
    $spreadsheet->disconnectWorksheets();
    unset($spreadsheet);
    //This file throws error when opened in Excel 2007+
    $i++;
 }
?>

I've checked the following things:

  1. There's no obvious php error messages, whitespace or extraneous input that are to be corrupting the file.
  2. The template file opens fine in Excel 2010.
  3. I've tried using different PHPExcel writer methods, but they all produce the same problem.

The real code does a whole load of extra stuff, but I've checked that it is not responsible by commenting it out. The code above seems to be the only place where a problem could be introduced.

Any suggestions gratefully received.

====EDITED====
This is the error log produced by Excel:

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
     <logFileName>error049120_01.xml</logFileName>
     <summary>Errors were detected in file 'C:\Users\USERNAME\AppData\Local\Temp\FILENAME.xlsx'</summary>
     -<additionalInfo>
           <info>Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.</info>
     </additionalInfo>
</recoveryLog>

Best Answer

I had a similar error on my file and followed the recommendation posted by Andrey Yanko, however I was still receiving similar errors. I found suggestions on another post and by adding an

"exit;"

at the end of my script that helped to remove the remaining errors

Related Topic