PHPExcel How to set a date in cell

折月煮酒 提交于 2019-12-19 20:37:14

问题


I need to put a date in a cell, when I take a look to its format it looks like *14/03/01.

The value I put is a simple string and for that reason when I get the calculated values ignores the date I entered because it compares in a calendar (well, a column with all the dates of the actual year) the date that I entered with the dates to set a proper value corresponding the date entered.

Is there a way to put the format that Excel expects?


回答1:


MS Excel uses a timestamp value for dates, and then masks it for display purposes; not a formatted string.

From 02types.php in the /Examples folder:

$dateTimeNow = time();    //  Get a Unix/PHP timestamp value for the date/time
$objPHPExcel->getActiveSheet()           // Convert Unix timestamp to a MS Excel 
    ->setCellValue('A9', 'Date/Time')    //  serialized timestamp, and set that as 
    ->setCellValue('B9', 'Date')         //  the cell value
    ->setCellValue(
        'C9', 
        PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow )
    );
$objPHPExcel->getActiveSheet()        // Format as date and time
    ->getStyle('C9')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);

The PHPExcel_Shared_Date::PHPToExcel() method will take a Unix timestamp or a string (formatted like those you might pass to strtotime()) and convert it to a MS Excel timestamp value; while the setFormatCode() calls are setting that cell to a format mask to indicate to MS Excel that the cell contains a value that should be displayed as a date and/or time




回答2:


$duree = '08:00:00';
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$sheet->setCellValueByColumnAndRow($row, $num, $duree);
$sheet->getStyleByColumnAndRow($row, $num)
      ->getNumberFormat()
      ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3);

And in my cell i can see 08:00



来源:https://stackoverflow.com/questions/22575173/phpexcel-how-to-set-a-date-in-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!