Read excel xlsx file using simplexlsx in php

MAK picture MAK · Apr 20, 2012 · Viewed 16.6k times · Source

I am using simplexlsx.class.php to read xlsx file type. It's giving problems when the file contain date field in the excel file.

Sample output:

In the file data:

Day Date Thursday 2/2/2012 Friday 2/3/2012

Program output:

Day Date

Thursday 40941
Friday 40942

It's not give the correct date

<?php

if (isset($_FILES['file'])) {

require_once "simplexlsx.class.php";

$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );

echo '<h1>Parsing Result</h1>';
echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';

list($cols,) = $xlsx->dimension();

foreach( $xlsx->rows() as $k => $r) {
    if ($k == 0) continue; // skip first row
    echo '<tr>';
    for( $i = 0; $i < $cols; $i++)
    {

        echo '<td>'.( (isset($r[$i])) ? $r[$i] : '&nbsp;' ).'</td>';

    }
    echo '</tr>';
}
echo '</table>';
}

?>
<h1>Upload</h1>
<form method="post" enctype="multipart/form-data">
*.XLSX <input type="file" name="file"  />&nbsp;&nbsp;<input type="submit" value="Parse" />

Answer

Mark Baker picture Mark Baker · Apr 20, 2012

Those are the correct dates, just in Excel's internal format: number of days since Jan 1st 1900 (allowing for 1900 being a leap year). Clearly something in the simplexlsx class is converting the xlsx date value to the Excel internal format.

I've not come across simplexlsx before (which surprises me as I thought I knew all the Excel file reader/writer libraries for PHP)... but somewhere in the code there must be a method to handle that conversion, so I'd imagine that there would also be a method for the reverse (converting Excel timestamp to PHP)

EDIT

The method you want is in the code:

function unixstamp( $excelDateTime ) {
    $d = floor( $excelDateTime ); // seconds since 1900
    $t = $excelDateTime - $d;
    return ($d > 0) ? ( $d - 25569 ) * 86400 + $t * 86400 : $t * 86400;
}

I make no guarantees that it's accurate

EDIT FURTHER

function unixstamp( $excelDateTime ) {
    $d = floor( $excelDateTime ); // seconds since 1900
    $t = $excelDateTime - $d;
    return ($d > 0) ? ( $d - 25569 ) * 86400 + $t * 86400 : $t * 86400;
}


$dateVal = 40941;
$unixDateVal = unixstamp($dateVal);
var_dump($unixDateVal);
echo date('d-M-Y',$unixDateVal);

gives

float 1328140800

which looks remarkably like a unix timestamp value in the correct range for this year, and sure enough:

02-Feb-2012

So looks like it works to me