phpexcel import time format and numeric format processing

/ ** 
 * Note: Import excel file 
 * User: hly 
 * Date: 2020/4/14 17:56 
 * / 
function importXlsx () 
{ 
    // Introduce phpexcel 
    require getcwd (). '/PHPExcel.php'; 
    $ file_name = 'test.xlsx'; // Simulate the uploaded file 
    $ objReader = \ PHPExcel_IOFactory :: createReader ('Excel2007'); 
    $ objPHPExcel = $ objReader-> load ($ file_name, $ encode = 'utf-8'); 
    $ sheet = $ objPHPExcel-> getSheet (0); 
    $ highestRow = $ sheet-> getHighestRow (); // Get the total number of rows 
    $ data = array (); 
    for ($ i = 2; $ i <= $ highestRow; $ i ++ ) { 
        $ data [$ i-2] ['title'] = getCellValue ($ objPHPExcel-> getActiveSheet ()-> getCell ("A". $ i));
        $data[$i - 2]['date_time'] = getCellValue($objPHPExcel->getActiveSheet()->getCell("B" . $i), 'Y-m-d H:i:s');
    }
    exit(json_encode($data));
}

function getCellValue($cell, $date_format = "Y-m-d H:i:s")
{
    $value = $cell->getValue();
    if($cell->getDataType() == \PHPExcel_Cell_DataType::TYPE_NUMERIC){
        //版本过低的话请加上 getParent 例:$cell->getParent()->getStyle($cell->getCoordinate())->getNumberFormat();
        $cell_style_format = $cell->getStyle($cell->getCoordinate())->getNumberFormat(); //不需要getParent
        $format_code = $cell_style_format->getFormatCode();
        if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i',$ format_code)) {// Determine whether it is a date type
            $ value = gmdate ($ date_format, \ PHPExcel_Shared_Date :: ExcelToPHP ($ value)); // format date 
        } else { 
            $ value = \ PHPExcel_Style_NumberFormat :: toFormattedString ($ value, $ format_code); // format number 
        } 
    } 
    return $ value; 
} 

importXlsx ();

  

Guess you like

Origin www.cnblogs.com/handle/p/12699660.html