Determine cell format (is it a date or not)

Topics: Developer Forum
Sep 2, 2009 at 10:27 AM

Hi all!

I have a problem to determine the format of a cell.
I need to know whether a cell is a date or not, since a user can upload any Excel file.

At the moment I do something like this:

$val = $cell->getCalculatedValue();

$type = $cell->getDataType();
$format = $this->objWorksheet->getStyle($cell->getCoordinate())->getNumberFormat()->getFormatCode();

// strpos($format, 'm') is the best guess for a date format
if ($type == 'n' && strpos($format, 'm') !== false) {
    $val = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($val));
}

This does not look very satisfying to me. How does it have to look? I just couldn't find any method which could do the job for me...

Thanks in advance,

Rainer

Coordinator
Sep 2, 2009 at 11:19 AM
$format = $this->objWorksheet->getStyle($cell->getCoordinate())->getNumberFormat()->getFormatCode();
$isDateFormat = PHPExcel_Shared_Date::isDateTimeFormatCode($format);
or
$isDateFormat = PHPExcel_Shared_Date::isDateTimeFormat($cell);
Sep 2, 2009 at 11:37 AM

Now I feel dumb!

Thank you for the enlightment, Mark!

 

Coordinator
Sep 2, 2009 at 11:52 AM

No need to feel dumb. Remember that we have a much better idea of what methods exist in which classes. The API documentation can go only so far, but you need to know what class to look in to find the methods listed there.

Sep 2, 2009 at 12:32 PM

Hi Mark!

I think 2<sup>nd</sup> example should be

$isDateFormat = PHPExcel_Shared_Date::isDateTime($cell);

instead of

$isDateFormat = PHPExcel_Shared_Date::isDateTimeFormat($cell);

Works great - same result as my old filthy workaround.

And this time I found the method in the API docs.

Thanks again!

Coordinator
Sep 2, 2009 at 1:33 PM

You're right. mea culpa. But you found the solution.

Now I feel dumb :-)