I'm try to output a date using PHPExcel where the format can be changed after generating the file.
So for example, I output the date, like this:
23/04/1989
And I can then format the cells, change the format and it shows something like:
April 23rd 1989
I've tried this approach (using the code below) and generated a file. When I click on the date cell and try to format it, it appears to have worked since it has the 'Date' category highlighted and the correct 'Type'.
However, if I change the format and click OK, the cell doesn't change it's format.
Here's my code:
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '23/04/1989');
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
Is this a limitation in Excel or am I not going about this the correct way?
You need to convert your date to an Excel serialized date/time stamp, and store that in the cell
$dateValue = PHPExcel_Shared_Date::PHPToExcel( strtotime('23-Apr-1989') );
$objPHPExcel->getActiveSheet()
->setCellValue('A1', $dateValue);
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
Note that PHPExcel_Shared_Date::PHPToExcel()
accepts a unix timestamp or a DateTime object
$dateValue = PHPExcel_Shared_Date::PHPToExcel(
DateTime::createFromFormat('d/m/Y', '23/04/1989')
);
$objPHPExcel->getActiveSheet()
->setCellValue('A1', $dateValue);
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
And as your date of 23/04/1989
would be treated as m/d/Y
by PHP (and therefore not what you'd expected - see PHP's accepted format rules ) using DateTime::createFromFormat()
allows you to specify that it's d/m/Y
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.