php 读取excel文件 支持 csv、xls、xlsx .thinkphp

项目需求要导入 各种excel文件 支持这三种类型。然后做下记录方便以后使用。


先是上附件 PHPExcel 文件 下载地址 百度 https://pan.baidu.com/s/1BmhnYd9arWqFD2jUCHUx8Q


下面我们来代码 tp 中放在




目录大概这样


控制器这样写。



   public function import_xls(){
//         echo 1;die;
//        $data=import_excel('./Upload/excel/simple.xls');
        $data=import_excel('./Upload/excel/2.xls');
        p($data);die;
    }

在 config 写入 

/**
 * 导入excel文件
 * @param  string $file excel文件路径
 * @return array        excel文件内容数组
 */
function import_excel($file){
    // 判断文件是什么格式
    $type = pathinfo($file);
    $type = strtolower($type["extension"]);

//    echo $type;die;
//    $type=$type==='xlsx' ? 'Excel2007' : 'Excel5';

    if($type=='xlsx'){

        $type=   'Excel2007';
    }elseif($type=='csv'){

        $type='csv';
    }else{
        $type='Excel5';

    }



//    echo $type;die;
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel.PHPExcel');
    // 判断使用哪种格式
    $objReader = PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($file);
    $sheet = $objPHPExcel->getSheet(0);
//    // 取得总行数
//    $highestRow = $sheet->getHighestRow();
//    // 取得总列数
//    $highestColumn = $sheet->getHighestColumn();
//    //循环读取excel文件,读取一条,插入一条
//    $data=array();
//    //从第一行开始读取数据
//    for($j=1;$j<=$highestRow;$j++){
//        //从A列读取数据
//        for($k='A';$k<=$highestColumn;$k++){
//            // 读取单元格
//            //数据坐标
//            $address=$k.$j;
//            //读取到的数据,保存到数组$arr中
//            $data[$j][]=$objPHPExcel->getActiveSheet()->getCell($address)->getValue();
//
//           // $data[$j][]=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
//        }
//    }
    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {     //遍历工作表
        //echo 'Worksheet - ' , $worksheet->getTitle() , PHP_EOL;
        foreach ($worksheet->getRowIterator() as $key=>$row) {       //遍历行
            //  echo $row->getRowIndex()."<br/>";
            $cellIterator = $row->getCellIterator();   //得到所有列
            $cellIterator->setIterateOnlyExistingCells( false); // Loop all cells, even if it is not set
            foreach ($cellIterator as $cell) {  //遍历列
                if (!is_null($cell)) {  //如果列不给空就得到它的坐标和计算的值
                    $rows[$key][]=   $cell->getCalculatedValue();
                }
            }
        }
    }
    return $rows;
}

调用  打印 值 




excel 文件






文章为原创 转载请注明地址  https://blog.csdn.net/qq_25861247/article/details/80376460

猜你喜欢

转载自blog.csdn.net/qq_25861247/article/details/80376460