Setting a cell with a date format in phpspreadSheet

Viewed 7738

I`'m trying to set some cells with date format in xslx(it's only a test script) file this way

<?php
    require 'vendor/autoload.php';

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
    \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A2',2);
    $sheet->setCellValue('A3',3);
    $sheet->setCellValue('A4',4);
    $sheet->setCellValue('A5',5);

    $time = gmmktime(0,0,0,12,31,2008);
    $sheet->setCellValue('B2', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExceldate($time));
    $sheet->setCellValue('B3', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExceldate($time));
    $sheet->setCellValue('B4', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExceldate($time));
    $sheet->setCellValue('B5', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExceldate($time));

    $writer = new Xlsx($spreadsheet);

    if(file_exists('prueba.xlsx'))
        unlink('prueba.xlsx');


    $writer->save('prueba.xlsx');

but I get this error message

Fatal error: Call to undefined method PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExceldate() in C:\xampp\htdocs\prueba_excel\index.php on line 16

I've included the autoload file, do I miss anything?

1 Answers

you need to put the use PhpOffice\PhpSpreadsheet\Spreadsheet; at the top of your php script, this way:

<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
Related