Laravel-Excel exported excel sheet doesn't convert date values in column to date

2.2k views Asked by At

I am using laravel-excel to export data in my database to an Excel worksheet. Columns containing dates are not interpreted as dates in Excel, so when I go to import this Excel file using laravel-excel, these columns aren't parsed and formatted correctly.

An example table:

table name: items
id  |   name    | some_date
===========================
1     Boxes       2014-11-13 17:00:00
2     Pickles     2016-12-01 13:30:00
...

My Laravel code:

Excel::create('SomeTitle', function($excel) {

    $items = Item::all()->toArray();

    $excel->sheet('SheetName', function($sheet) use($items) {
        $sheet->fromArray($items, null, 'A1', true);
    });
})->export('xls');

Now, in the exported Excel file, column C (which is "some_date") will contain a date like 2014-11-13 17:00:00, but Excel will not recognize this as a date - so when I import the tile using laravel-excel, it will not automatically be converted to an instance of Carbon.

When I use $sheet->setColumnFormat(array('C' => 'yyyy-mm-dd')); and import the Excel file again, laravel-excel will now recognize and convert the date to a Carbon instance, but the date, time and days will be completely off!

The only way Excel will recognize the cells in the column as dates is if I click on the column, and click away. Excel then automatically converts it to a date.

How can I ensure that the some_date column is automatically converted to a date when I export the file?

1

There are 1 answers

0
Matt Burrow On

If you want to return extra columns as Carbon instances add the following to your model;

public function getDates(){
    return array('created_at','updated_at','some_date');
}

This will return it as an instance of Carbon automatically. So in theory whenever it tries to print out the instance it should be printed out as a string.