PHP 导出 Excel 兼容 CSV XlS格式
阅读原文时间:2023年07月10日阅读:3

class ExcelRead
{

/\*\*  
 \* 获取Excel文件内容  
 \* @param $file  
 \* @return mixed  
 \* @throws PHPExcel\_Reader\_Exception  
 \* @author Starfish  
 \* @date 2020-06-09 11:29  
 \*/  
public function getExcelFileData($file) {

    $file\_types = explode ( ".", $file\['name'\] );  
    $file\_type = strtolower(end($file\_types));  
    $excel\_type = array('xls','csv','xlsx');  
    if (!in\_array($file\_type,$excel\_type)){  
        echo 'file type error';exit;  
    }

    $inputFileType = PHPExcel\_IOFactory::identify($file\['tmp\_name'\]);  
    if($file\_type == 'csv') {  
        $objReader = PHPExcel\_IOFactory::createReader($inputFileType)  
            ->setDelimiter(',')  
            ->setInputEncoding('GBK')  //新版本可删除  
            ->setSheetIndex(0);  
    }else {  
        $objReader = PHPExcel\_IOFactory::createReader($inputFileType);  
    }

    $objPHPExcel = $objReader->load($file\['tmp\_name'\]);

    $res = $objPHPExcel->getActiveSheet()->toArray();  
    foreach ($res as $k => $v) {  
        // 空值处理  
        if(!$v\['0'\]) {  
            unset($res\[$k\]);  
        }  
    }

    return $res;  
}  

}