简体   繁体   English

PHPExcel将字符串日期放入.xls

[英]PHPExcel putting string date into .xls

guys. 家伙。 I have dates at DB as strings "d/m/Y". 我在DB的日期为字符串“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 . 当我把这个日期放到Excel中时,它会显示正常日期,如03/10/2000,但是当我点击单元格时,它会显示值'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 : 所以,我将日期从DB转换为PHP日期对象,并确保var_dump日期是具有该代码的Date对象:

$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. 但无论如何,生成的.xls中的值都是'之前的值。

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). MS Excel将日期存储为序列化时间戳,即自1900年1月1日(或1904年1月1日,如果使用Mac日历)以来的天数。 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 将$ excelDate设置为单元格值

$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 `/ Examples`文件夹中02types.php示例脚本演示了这一点

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. 您可以(并且更有效)将样式应用于一系列单元格:只需在getStyle()调用中指定范围即可。

$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 . 要获取可用格式的详细信息:PHPExcel内置了许多预定义的格式,这些格式可以在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 并且(与MS Excel允许您定义“自定义”格式的方式相同)您可以使用几乎任何可用于MS Excel规则来传递定义格式的字符串(例如“d-mmm-yyyy”) 数字格式掩码作为格式

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

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