问题
Sometimes I'm unable to format an Excel cell data as date using $date
wiht format 'yyyy-mm-dd' (eg. 2017-07-12)
if ($date != '') {
$t_date = PhpOffice\PhpSpreadsheet\Shared\Date::stringToExcel($date);
$sheet->setCellValueByColumnAndRow($column,$row, $t_date);
$sheet->getStyleByColumnAndRow($column,$row)->getNumberFormat()->setFormatCode(PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
}
回答1:
The previous code fails when a $date
is not valid (eg. 0000-00-00), and keeps failing in all sequent applies.
My solution is
if ($date != '') {
$t_date = PhpOffice\PhpSpreadsheet\Shared\Date::stringToExcel($date);
if ($t_date !== false) {
$sheet->setCellValueByColumnAndRow($column,$row, $t_date);
$sheet->getStyleByColumnAndRow($column,$row)->getNumberFormat()->setFormatCode(PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DDMMYYYY);
$sheet->getStyleByColumnAndRow($column,$row)->getFont()->setBold(true);
$sheet->getStyleByColumnAndRow($column,$row)->getFont()->setBold(false);
}
}
Settting and unsetting the bold stile kwwpd working the setFormatCode in moste fo the cases ... I do not know why.
来源:https://stackoverflow.com/questions/47883697/phpspreadsheet-setformatcode-not-working