简体   繁体   中英

PHPExcel putting string date into .xls

guys. I have dates at DB as strings "d/m/Y". When I put this dates into Excel, it shows me normal dates like 03/10/2000, but when I click on the cell, it show me the value '03/10/2000 . So, the value is string, and not date as required for me.

So, I transformed the date from DB to a PHP date object and get sure with var_dump that date is Date object with that code :

$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
              $date->format('m/d/Y');

but anyway, the values in generated .xls are with ' before value.

Why it appears and how can I solve it ?

MS Excel stores dates as a serialized timestamp, the number of days since 1st January 1900 (or 1st January 1904 if using the Mac calendar). To store a value as a date (and not simply as a string), you need to convert your string date to a serialized timestamp, and then set the format mask for the cell.

$date = date_create_from_format('d/m/Y', $array[$i-20]['Date']);
$excelDate = PHPExcel_Shared_Date::PHPToExcel($date);

Set $excelDate as the cell value

$objPHPExcel->getActiveSheet()->setCellValue('C11', $excelDate );

and then apply the format mask to that cell

$objPHPExcel->getActiveSheet()
    ->getStyle('C11')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);

The 02types.php example script in the `/Examples` folder demonstrates this

EDIT

You can (and it's more efficient to) apply a style to a range of cells: just specify the range in the getStyle() call.

$objPHPExcel->getActiveSheet()
    ->getStyle('C11:C200')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);

To get details of available format: PHPExcel has a number of pre-defined formats built-in, and those can be found as constants in Classes/PHPExcel/Style/NumberFormat.php . However, you're not limited to that set of formats; and (in the same way that MS Excel lets you define "custom" formats) you can simply pass a string defining the format (eg "d-mmm-yyyy") using pretty much any of the rules that can be used for MS Excel number format masks as the format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM