首页 > 解决方案 > 如何使用 PHPExcel 库读取 Excel 单格日期(DD/MM/YYYY)值并将日期格式转换为(M/D/YYYY)

问题描述

我正在使用 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 单元格值,以便我可以转换它。

注意:在 excel 中,我试图获取的 B2 单元格值仅是日期格式。但它的变化取决于我的 excel 默认语言。

如果您需要更多信息,请告诉我。我希望我能在这里解决。

提前致谢。

由阿甘

标签: phpexcelcsvphpexceldate-formatting

解决方案


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

使用此代码:


$excel_date = $csv[1][1];  //22/6/2019;   
$changed_date = DateTime::createFromFormat('d/m/Y', $excel_date)->format('D/M/Y');
echo $changed_date;

对于您决定哪种格式是 excel 日期的要求,请使用以下代码:


function convert_date_format($old_date = '')     {  
 $old_date = trim($old_date);        
    if (preg_match('/^(0[1-9]|1[0-2]|[1-9])\/(0[1-9]|[1-2][0-9]|3[0-1])\/[0-9]{4}$/', $old_date)) // MySQL-compatible YYYY-MM-DD format  
     {   return 'm/d/Y';     }   
     elseif (preg_match('/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2]|[1-9])\/[0-9]{4}$/', $old_date)) // DD-MM-YYYY format  
     {   return 'd/m/Y';
     }    
 }

$excel_format = convert_date_format($excel_date);
$changed_date = DateTime::createFromFormat($excel_format, $excel_date)->format('D/M/Y');
echo $changed_date;


推荐阅读