简体   繁体   English

在PHPExcel中格式化可以在生成XLS之后更新的日期

[英]Formatting a date in PHPExcel that can be updated after XLS is generated

I'm try to output a date using PHPExcel where the format can be changed after generating the file. 我尝试使用PHPExcel输出日期,在生成文件后可以更改格式。

So for example, I output the date, like this: 因此,例如,我输出日期,如下所示:

23/04/1989 23/04/1989

And I can then format the cells, change the format and it shows something like: 然后,我可以格式化单元格,更改格式,它显示如下内容:

April 23rd 1989 1989年4月23日

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? 这是Excel中的限制吗?还是我没有正确的方法呢?

You need to convert your date to an Excel serialized date/time stamp, and store that in the cell 您需要将日期转换为Excel序列化的日期/时间戳,并将其存储在单元格中

$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 请注意, PHPExcel_Shared_Date::PHPToExcel()接受unix时间戳或DateTime对象

$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 而且由于PHP使用DateTime::createFromFormat()将您的日期为23/04/1989日视为m/d/Y (因此不是您所期望的-请参见PHP 接受的格式规则 ),它允许您指定它的日期为d/m/Y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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