在phpspreadSheet中设置日期格式的单元格

时间:2018-09-07 08:12:59

标签: php phpspreadsheet

我正在尝试以这种方式在xslx(这只是一个测试脚本)文件中设置一些日期格式的单元格

<?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');

但我收到此错误消息

  

致命错误:在第16行的C:\ xampp \ htdocs \ prueba_excel \ index.php中调用未定义的方法PhpOffice \ PhpSpreadsheet \ Shared \ Date :: PHPToExceldate()

我已包含自动加载文件,我会错过任何内容吗?

1 个答案:

答案 0 :(得分:0)

你需要把使用 PhpOffice\PhpSpreadsheet\Spreadsheet; 放在你的 php 脚本的顶部,这样:

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