How to format dates in PHPExcel?

时间:2017-04-10 02:34:05

标签: phpexcel date-formatting

So, I'm a fairly new PHP programmer and I'm trying to set up a page that uploads a file, displays the info in a table, then writes the data to a database.

I've got these things working (I found some helpful code online) however my dates are displaying incorrectly.

For example, the date "2/15/2017 17:55" is displaying as "42781.746527778".

Here is the code:

    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName); 
        $objReader = PHPExcel_IOFactory::createReader($inputFileType); 
        $objPHPExcel = $objReader->load($inputFileName); 

    } catch (Exception $e) {
        die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) 
        . '": ' . $e->getMessage());
    }


    echo '<center><table style="width:50%;" border=1>';


    $sheet = $objPHPExcel->getSheet(0);     
    $highestRow = $sheet->getHighestRow();     
    $highestColumn = $sheet->getHighestColumn();     


    for ($row = 1; $row <= $highestRow; $row++) {



        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
        NULL, TRUE, FALSE);


        echo "<tr>";


        foreach($rowData[0] as $k=>$v)
            echo "<td>".$v."</td>";

        echo "</tr>";
    }

    echo '</table></center>';

}

else{
    echo '<p style="color:red;">Please upload file with xlsx extension only.</p>'; 
} 

I get why it is displaying the date that way, however I'm not having luck in fixing it when trying to display the entire column as a date and time, or displaying it in a single cell as the correct date and time.

var_dump($objPHPExcel->getActiveSheet()->getCell('B2')->getFormattedValue());

This code displays the correct date and time for one of my sample spreadsheets, however I'm not able to get that value in the cell.

Any help would be appreciated. Thank you!

1 个答案:

答案 0 :(得分:1)

我相信这就是你要找的东西?检查单元格是否为Excel日期和时间,然后提取Excel日期并将其转换为PHP日期。

if(PHPExcel_Shared_Date::isDateTime($k)) {
    $v = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($v));
}