Laravel excel maatwebsite 3.1 导入,excel 单元格 returns 中的日期列为未知格式数字。如何解决这个问题?

Laravel excel maatwebsite 3.1 import, date column in excel cell returns as unknown format number. How to solve this?

通过使用Maatwebsite/Laravel-Excel 3.1 版导入excel sheet,这里我遇到了 excel sheet [=19] 的问题日期时间列=] 未知数。如何解决这个问题?示例:导入时将单元格值“29/07/1989”和 returns 视为“32178”。

The numbers come from excel itself, dates stored in excel as numeric values. http://www.cpearson.com/excel/datetime.htm

For Laravel framework 5.6 and maatwebsite/excel package version 3.1, to convert date from excel numbers to normal date format, this function PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($dateFromExcel) can be used. It accepts integer(excel date) and returns DateTime object.

More information can be found here https://github.com/Maatwebsite/Laravel-Excel/issues/1832

来自这个答案:

已解决!这是我用来解决问题的代码:

Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));

我尝试了上述解决方案,但总是遇到 non-numeric 值错误

我设法使用

解决了这个问题

$date = intval($row['value']);

\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($date)->format('d/m/Y')

那个“未知数”是一个 excel 时间戳,这样它就可以在内部存储日期和时间数据。

例如:

123213.0: it's just a date
213233.1233: is a date and time
0.1233: it's one hour

如果您可以映射单元格并且您知道哪一列将始终具有日期/时间/日期时间,您可以使用映射单元格或手动转换它,请参阅:

否则,如果您的需求涉及动态解析日期时间字段,我已经编写了一个方法,负责自动检测该值是否为动态日期时间(无论您是否知道其中是否有日期时间)列)或者我已经尝试了各种数据类型并且工作正常

   /**
 * @param Cell $cell
 * @param $value
 * 
 * @return boolean;
 */
public function bindValue(Cell $cell, $value)
{
    $formatedCellValue = $this->formatDateTimeCell($value, $datetime_output_format = "d-m-Y H:i:s", $date_output_format = "d-m-Y", $time_output_format = "H:i:s" );
    if($formatedCellValue != false){
        $cell->setValueExplicit($formatedCellValue, DataType::TYPE_STRING);
        return true;
    }

    // else return default behavior
    return parent::bindValue($cell, $value);
}


/**
 * 
 * Convert excel-timestamp to Php-timestamp and again to excel-timestamp to compare both compare
 * By Leonardo J. Jauregui ( @Nanod10 | siskit dot com )
 * 
 * @param $value (cell value)
 * @param String $datetime_output_format
 * @param String $date_output_format
 * @param String $time_output_format
 * 
 * @return $formatedCellValue
 */
private function formatDateTimeCell( $value, $datetime_output_format = "Y-m-d H:i:s", $date_output_format = "Y-m-d", $time_output_format = "H:i:s" )
{

    // is only time flag
    $is_only_time = false;
    
    // Divide Excel-timestamp to know if is Only Date, Only Time or both of them
    $excel_datetime_exploded = explode(".", $value);

    // if has dot, maybe date has time or is only time
    if(strstr($value,".")){
        // Excel-timestamp to Php-DateTimeObject
        $dateTimeObject = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value);
        // if Excel-timestamp > 0 then has Date and Time 
        if(intval($excel_datetime_exploded[0]) > 0){
            // Date and Time
            $output_format = $datetime_output_format;
            $is_only_time = false;
        }else{
            // Only time
            $output_format = $time_output_format;
            $is_only_time = true;
        }
    }else{
        // Only Date
        // Excel-timestamp to Php-DateTimeObject
        $dateTimeObject = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value);
        $output_format = $date_output_format;
        $is_only_time = false;
    }
        
    // Php-DateTimeObject to Php-timestamp
    $phpTimestamp = $dateTimeObject->getTimestamp();

    // Php-timestamp to Excel-timestamp
    $excelTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $phpTimestamp );
        
    // if is only Time
    if($is_only_time){
        // 01-01-1970 = 25569
        // Substract to match PhpToExcel conversion
        $excelTimestamp = $excelTimestamp - 25569;
    }

    /* 
    // uncoment to debug manualy and see if working
    $debug_arr = [
            "value"=>$value,
            "value_float"=>floatval($value),
            "dateTimeObject"=>$dateTimeObject,
            "phpTimestamp"=>$phpTimestamp,
            "excelTimestamp"=>$excelTimestamp,
            "default_date_format"=>$dateTimeObject->format('Y-m-d H:i:s'),
            "custom_date_format"=>$dateTimeObject->format($output_format)
        ];
        
    if($cell->getColumn()=="Q"){
        if($cell->getRow()=="2"){
            if(floatval($value)===$excelTimestamp){
                dd($debug_arr);
            }
        }
    }

    */
    
    // if the values match
    if( floatval($value) === $excelTimestamp ){
        // is a fucking date! ;)
        $formatedCellValue = $dateTimeObject->format($output_format);
        return $formatedCellValue;
    }else{
        // return normal value
        return false;
    }
    
}

根据Skyrem Brilliant@skyrem-brilliant 的回答,我是这样解决的:

<?php

//...

class YourExcelImport implements OnEachRow, WithValidation, WithHeadingRow
{
   // ...

    /**
     * Tweak the data slightly before sending it to the validator
     * @param $data
     * @param $index
     * @return mixed
     */
    public function prepareForValidation($data, $index)
    {
        //Fix that Excel's numeric date (counting in days since 1900-01-01)
        $data['your_date_column'] = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($data['your_date_column'])->format('Y-m-d');
        //...
    }

    /**
     * List the validation rules
     * @return array
     */
    public function rules(): array
    {
        return [
            'your_date_column'=>'required|date_format:Y-m-d',
            //..
        ];
    }
}
?>

成功了,验证通过了。

简单的使用这个函数来存储日期。

use PhpOffice\PhpSpreadsheet\Shared;

public function collection(Collection $collection)
{
    $errors = $this->validateBulk($collection);
    if (!empty($errors)) {
        return;
    }

    $holidays = [];
    foreach ($collection as $col) {
        Validator::make($col->toArray(), $this->rules())->validate();
        $holidays[] = [
            'title' => $col['title'],
            'holiday_date' => Date::excelToDateTimeObject($col['holiday_date'])
                ->format('y-m-d'),
            'holiday_year' => Date::excelToDateTimeObject($col['holiday_date'])
                ->format('y'),
        ];
        $this->rows++;
    }
    
    Holidays::insert($holidays);
}