PHP 导入 Excel 文件中的日期数据,通常涉及到处理 Excel 文件格式(如 XLSX 或 CSV)中的日期和时间数据。Excel 中的日期是以从 1900 年 1 月 1 日开始的天数来表示的,这与 PHP 的日期处理方式有所不同。
phpoffice/phpspreadsheet 库来处理。<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
// 读取 Excel 文件
$inputFileName = 'example.xlsx';
$spreadsheet = IOFactory::load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();
// 遍历日期数据
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // 遍历所有单元格,包括空单元格
foreach ($cellIterator as $cell) {
if ($cell->isDate()) {
// 获取 Excel 中的日期值
$dateValue = $cell->getValue();
// 转换为 PHP 日期时间
$dateTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($dateValue);
echo $dateTime->format('Y-m-d') . PHP_EOL;
}
}
}
?><?php
$inputFileName = 'example.csv';
if (($handle = fopen($inputFileName, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if (strtotime($data[$c])) {
// 转换为 PHP 日期时间
$dateTime = date('Y-m-d', strtotime($data[$c]));
echo $dateTime . PHP_EOL;
}
}
}
fclose($handle);
}
?>原因:Excel 和 PHP 对日期的处理方式不同,Excel 使用的是从 1900 年 1 月 1 日开始的天数,而 PHP 使用的是 Unix 时间戳。
解决方法:使用 PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject 函数将 Excel 中的日期转换为 PHP 的 DateTime 对象。
原因:CSV 文件中的日期格式可能因地区或用户设置而异。
解决方法:使用 strtotime 函数尝试解析日期,并根据需要调整日期格式。
通过以上方法,可以有效地处理 Excel 文件中的日期数据,并将其转换为 PHP 可以处理的格式。
没有搜到相关的沙龙