如何在PHPSpreadsheet中更改日期时间格式?

时间:2019-05-03 16:09:24

标签: php phpspreadsheet

我使用PHPspreadsheet将xlsx文件转换为csv文件。

在“ I”列中,我有类似[26-04-2019 07:57:35]的日期和时间,如何将其更改为[2019-04-26 07:57:35]

我想更改它以便上传到MYSQL。

use \PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use \PhpOffice\PhpSpreadsheet\Writer\Csv;

$xls_file = "$file";

$reader = new Xlsx();
$spreadsheet = $reader->load($xls_file);


$loadedSheetNames = $spreadsheet->getSheetNames();

$writer = new Csv($spreadsheet);

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $writer->setSheetIndex($sheetIndex);
    $writer->save($loadedSheetName.'.csv');
}

1 个答案:

答案 0 :(得分:0)

您将需要遍历每张纸的每一行,并将列I更改为MySQL所需的格式。

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $writer->setSheetIndex($sheetIndex);
    $worksheet   = $spreadsheet->getActiveSheet();
    $highestRow  = $worksheet->getHighestRow(); // e.g. 10

    for ($row = 1; $row <= $highestRow; ++$row) {
        $datenow = $worksheet->getCellByColumnAndRow(9,$row)->getValue();
        $worksheet->setCellValue('I' . $row,date('Y-m-d h:i:s',strtotime($datenow)));

    }  // end of for loop through the sheet

    $writer->save($loadedSheetName.'.csv');
}