Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel How to set a date in cell

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?

like image 402
xmarston Avatar asked Dec 25 '22 11:12

xmarston


2 Answers

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

like image 199
Mark Baker Avatar answered Dec 28 '22 06:12

Mark Baker


$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

like image 37
Xman Classical Avatar answered Dec 28 '22 08:12

Xman Classical