如何使用PHPExcel库读取Excel的一个单元格日期(DD / MM / YYYY)值并将日期格式转换为(M / D / YYYY)

问题描述 投票:0回答:1

我正在使用php PHPExcel库将excel文件数据转换为csv文件。目前,我正在将所有数据从excel导入csv。但是我需要在一个特定的单元格中更改日期格式[例如。 B2]在Excel的日期(DD / MM / YYYY)中,我想将其更改为M / D / YYYY,并将其更改为csv。

注意:我正在使用phpexcel库来读取excel fi

我尝试了以下代码:

<?php
$excel_lib = '/var/www/mp/cronfiles/data/Classes/PHPExcel/IOFactory.php';
include($excel_lib);
$filearray = array('file1.xlsx','file2.csv','file3.csv');
$file2 = fopen(dirname(__FILE__).'/'.$filearray[0],"r");
if (!$file2) {
                echo "File not exisit";
            }
$inputFileType1 = PHPExcel_IOFactory::identify($filearray[0]);
$objReader1 = PHPExcel_IOFactory::createReader($inputFileType1);
$objPHPExcel1 = $objReader1->load($filearray[0]);
$sheet1 = $objPHPExcel1->getSheet(0);

      $highestRow1 = $sheet1->getHighestRow();

      $highestColumn1 = $sheet1->getHighestColumn();

      $rowData1 = array();

  for ($row1 = 1; $row1 <= $highestRow1; $row1++) { 
    $rowData1[] = $sheet1->rangeToArray('A' . $row1 . ':' . $highestColumn1 . $row1, null, true, true);
  }

  foreach($rowData1 AS $k => $v){
      foreach ($v AS $fk => $fv){
          $csv[] = $fv;
          }
      }

$excel_date = 'As of '.$csv[1][1]; //its B2 cell in excel value ex.[echo $excel_date; output 22/6/2019]
$changed_date = date_format('M/d/Y', $excel_date);
echo $change_date;

我遇到以下错误:

警告:date_format()期望参数1为DateTimeInterface,在var / www / html / mp / cronfiles / data / myfile.php **中给出的字符串**

我的问题:1.如何获取日期格式的excel单元格值,以便我可以将其转换。

Note:在excel中,我尝试获取的B2单元格值仅采用日期格式。但其更改取决于我的excel默认语言。

请让我知道是否需要更多信息。我希望我能在这里解决。

提前感谢。

由Agan

php excel csv phpexcel date-formatting
1个回答
0
投票

您收到的日期格式为excel日期格式。首先,您必须转换为php datetime格式,然后转换为所需的输出格式。

使用此代码:


$excel_date = $csv[1][1];  //22/6/2019; 
$excel_date = strtotime($excel_date);  
$changed_date = date_format('M/d/Y', $excel_date);
echo $change_date;

$excel_date = $csv[1][1];  //22/6/2019; 
$excel_date = strtotime($excel_date);  
$change_date = date(''M/d/Y', $excel_date);
echo $change_date;
© www.soinside.com 2019 - 2024. All rights reserved.