在我的excel文件中,我是从PHP构建的,第一行是标题。我需要将几个日期作为列标题。每个日期(年/月/日/年格式)15 / mm / yyyy从2007年1月15日开始,到15/12/2018逐月踩踏。 我的代码是这样的:
for($anno = $annoMin; $anno<=$annoMax; $anno++){
for($mese = 1; $mese <= 12; $mese++){
$mese = sprintf("%02s", $mese);
$periodo = '15/'.$mese.'/'.$anno;
$periodo = strtotime($periodo);
$periodo = PHPExcel_Shared_Date::PHPToExcel($periodo);
array_push($header_array,$periodo);
}
}
我将日期构建为字符串,将其转换为unix时间戳,将其转换为excel日期并将其推送到$ header_array。 然后我在excel中绘制单元格:
$ews->fromArray($header_array, ' ', 'A1');
最后,我将有日期的单元格格式化为:
$ews->getStyle('U1:EJ1')
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY);
问题是:
对于第一个问题:我检查了不同的SO问题并遵循mainly this one。没有运气。
答案 0 :(得分:2)
问题出在这里:
$periodo = '15/'.$mese.'/'.$anno;
$periodo = strtotime($periodo);
这将给出15/1/2015
,15/2/2015
...``15/12/2015 that you're then attempting to convert to a unix timestamp using
strtotime()`的字符串值。
如果您阅读strtotime()
函数使用的PHP Docs on date formats,您会看到/
分隔符告诉PHP日期字符串是美国日期格式....即mm / dd / yyyy giving a month value of
15`在每种情况下,(当然)没有第15个月
使用短划线(-
)而不是/
来表示欧洲(dd-mm-yyyy
)而不是美国日期格式
$periodo = '15-'.$mese.'-'.$anno;
$periodo = strtotime($periodo);
或重新排序值以使用美国格式
$periodo = $mese.'/'.'15/'.$anno;
$periodo = strtotime($periodo);
对于你问题的第二部分......你可以提供几乎任何MS Excel识别的格式掩码,你不仅限于内置格式;这样:
$ews->getStyle('U1:EJ1')
->getNumberFormat()
->setFormatCode('mm/yyyy');
格式代码只是一个字符串值