如何在从excel导入数据时使用phpexcel更改日期格式?

时间:2018-02-07 15:41:41

标签: php mysql excel date phpmyadmin

我有excel文件(.xls),在该文件中我有日期字段,格式如下:21/07/1989

在上传日期更改格式从21/07/1989 210789

之后,我尝试在localhost上传到数据库(phpmyadmin)

我想问一下如何将phpmyadmin中的格式日期从210789更改为 21/07/1989

在数据库(phpmyadmin)类型的日期我设置为文本但不生效

这是我的导入文件xls到数据库的代码:

<?php
 //export.php
 if(!empty($_FILES["excel_file"]))
 {
      $connect = mysqli_connect("localhost", "root", "", "myname_database");

     mysqli_query($connect,"SET CHARACTER SET 'utf8'");
      $file_array = explode(".", $_FILES["excel_file"]["name"]);
      if($file_array[1] == "xls")
      {  
           include("PHPExcel/IOFactory.php");
           $output = '';
           $output .= "
           <label class='text-success'>Data Inserted</label>
                <table class='table table-bordered'>
                     <tr>  
                          <th>No</th>
                          <th>Nama</th>
                          <th>Date of birth</th>
                     </tr>
                     ";
           $object = PHPExcel_IOFactory::load($_FILES["excel_file"]["tmp_name"]);
           foreach($object->getWorksheetIterator() as $worksheet)
           {
                $highestRow = $worksheet->getHighestRow();
                for($row=1; $row<=$highestRow; $row++)
                {
                     $no = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(0, $row)->getValue());
                     $nama = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(1, $row)->getValue());
                     $date_birth = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(2, $row)->getValue());
                     $query = "
                     INSERT INTO myname_table
                     (no, nama, date_birth)
                     VALUES ('".$no."', '".$nama."', '".$date_birth."')
                     ";
                     mysqli_query($connect, $query);
                     $output .= '
                     <tr>
                          <td>'.$no.'</td>
                          <td>'.$name.'</td>
                          <td>'.$date_birth.'</td>

                     </tr>
                     ';
                }
           }
           $output .= '</table>';
           echo $output;
      }
      else
      {
         echo '<label class="text-danger">Invalid File</label>';
      }
 }
?>

1 个答案:

答案 0 :(得分:0)

而不是在数据库中再次操纵值,您应该更喜欢在从Excel中检索时格式化值。

对包含日期的字段进行getValue()调用时,应返回210789之类的值。要获取格式化的日期字符串,您需要调用getFormattedValue()。要确定某个单元格是否包含MS序列化日期时间戳,您可以使用对PHPExcel_Shared_Date::isDateTime()的调用。

$cell = $worksheet->getCellByColumnAndRow(2, $row);
if (PHPExcel_Shared_Date::isDateTime($cell)) {
   echo $cell->getFormattedValue();
} else {
    echo $cell->getValue();
}