Sunday, August 14, 2011

PHP Pear Spreadsheet Write - File Error: Data may have been lost

I needed to write out data to a spreadsheet file so I installed PHP PEAR's Spreadsheet Excel Writer. It is pretty easy to use. I wrote the code I needed but kept getting the following error upon opening the file:
File Error: Data may have been lost.

So then I went to PHPExcel, however, when I installed the code to production I realized it was still on PHP4, and that only works with PHP5...

So I went back to the Spreadsheet Excel Writer. I noticed that the files opened just fine, and all the data was there, so it really worked, however, I imagined fielding calls from user's asking what the error was...and I felt it would be more credible if I did not have this error popping up.

So along the way I figured out what caused the error for myself. I had several 'for loops' that wrote out data like this:

foreach ($collection as $key => $value)
{
$value = trim($value);

if($value != "")
$sheet->write($index,$cellLetter, $value);

}

So I replaced the 'for loops' with the 'writeCol' function that would write out an entire collection into a column.

$sheet->writeCol (8 , 3 , $collection);

This worked for almost every instance where I was looping thru collections, there was one instance where I could not apply this logic, but since it was only about 10 lines of repeating code, I opted to do that rather than cause the Data Lost error. So I am pretty happy with that.

If we ever upgrade to PHP5, I will consider just using the PHPExcel code since I never had the Data Lost error with it.

Hope that helps!