Reputation: 79
I'm trying to import data from excel file to database using maatwebsite excel package
,
I'm using the following code :
namespace App\Imports;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Spreadsheet\Shared\Date;
use App\Models\Casting;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Auth;
class ProjectsImport implements ToModel,WithHeadingRow,WithValidation
{
use Importable;
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
$casting = new Casting();
$casting->date_naissance = Date::excelToTimestamp($row['date_naissance']);
}
}
But doens't work , I get the following error :
"message": "Class 'PhpOffice\\PhpSpreadsheet\\Spreadsheet\\Shared\\Date' not found",
If you have any idea please help !
Upvotes: 2
Views: 667
Reputation: 1906
use the Carbon date function. Note that the imported file format should be a CSV file.
Carbon::createFromFormat('d/m/Y', $row['date_column']);
Upvotes: 0
Reputation: 11
This is work for me in latest version of maatwebsite excel/laravel package.
$excel_date = $row[13]; //Your row line date that is : 3/17/2022
$uniq_date = ($excel_date - 25569) * 86400;
$date = gmdate('Y-m-d H:i:s', $uniq_date);
dd($date);
Output : "2022-03-17 00:00:00"
Upvotes: 0
Reputation: 382
When you use dd()
on the date column from Excel you'll see that the data comes parsed as a number WITHOUT ANY SEPARATORS. The lack of separators is what brings about the challenge as your database will be expecting data in DATE format but you will be trying to update/create a record with an integer.
SOLUTION
You can use the PHP Carbon Extension for Date and Time to convert Excel date format into PHP date format.
Simply go through the documentation and you should be up and running in no time.
Upvotes: 1