phpexcel读取excel的xls xlsx csv格式

<?php
  
class Excel
{
    public $currentSheet;
    public $filePath;
    public $fileType;
    public $sheetIndex=0;
    public $allColumn;
    public $allRow;
    public function initialized($filePath) {
        if (file_exists($filePath)) {
            $this->filePath=$filePath;
        }else{
            return array();
        }
        //以硬盘方式缓存
        $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
        $cacheSettings = array();
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
        $file_ext=strtolower(pathinfo($this->filePath, PATHINFO_EXTENSION));
        switch ($file_ext) {
            case 'csv':
                $this->fileType='csv';
                break;
            case 'xlsx':
                $this->fileType='excel';
                break;
            case 'xls':
                $this->fileType='excel';
                break;
            default:
                $this->fileType='';
                break;
        }
        
        if ($this->fileType=='csv') {
            $PHPReader = new PHPExcel_Reader_CSV();
  
            //默认字符集
            $PHPReader->setInputEncoding('GBK');
  
            //默认分隔符  
            $PHPReader->setDelimiter(',');
  
            if(!$PHPReader->canRead($this->filePath)){
                return array();
            }
        }elseif ($this->fileType=='excel'){
            $PHPReader = new PHPExcel_Reader_Excel2007();
  
            if(!$PHPReader->canRead($this->filePath)){
                $PHPReader = new PHPExcel_Reader_Excel5();
  
                if(!$PHPReader->canRead($this->filePath)){
                    return array();
                }
            }
        }else{
            return array();
        }
  
        $PHPReader->setReadDataOnly(true);
        $PHPExcel = $PHPReader->load($this->filePath);
        $this->currentSheet = $PHPExcel->getSheet((int)$this->sheetIndex);
        //$this->currentSheet = $PHPExcel->getActiveSheet();
        $this->allColumn=$this->currentSheet->getHighestColumn();
        $this->allRow=$this->currentSheet->getHighestRow();
    }
  
    public function fetch($beginRow=NULL, $endRow=NULL){
        $currentSheet=$this->currentSheet;
        $allColumn=$this->allColumn;$allRow=$this->allRow;
        $dataSrc=$data=array();
        
        //获取列标题
        for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
            $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, 1)->getValue();//ord()將字符转为十进制数  
            $dataSrc[ord($currentColumn) - 65]=strtolower(trim($val));}
            //echo implode("\t", $dataSrc);
            $beginRow=$beginRow ? $beginRow : 2;
            $endRow=$endRow ? $endRow : $allRow;
            for($currentRow = $beginRow ;$currentRow <= $endRow ;$currentRow++){
                //从第A列开始输出$dataRow=array();
                for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
                    $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();//ord()將字符转为十进制数  
                    $dataRow[$dataSrc[ord($currentColumn) - 65]]=$val;
                    //单元级数据处理 ... 格式化日期等  
                }
  
                //行级数据处理 ...  
  
                if($dataRow){
                    $data[]=$dataRow;}
            }
  
            //echo '<pre>', print_r($data), '</pre>';
  
            //echo "\n";
        return $data;
    }
}



require_once 'Classes/PHPExcel.php';
$import=new Excel(); 
$import->initialized(dirname(__FILE__) . '/test.xlsx'); 
header("Content-type: text/html; charset=utf-8"); 
echo '<pre>', print_r($import->fetch()), '</pre>';
   if(Yii::$app->request->isPost){

            $fname = $_FILES['filename']['name'];
            $ftype = pathinfo($fname, PATHINFO_EXTENSION);
            if (!in_array($ftype, ['xls', 'xlsx', 'csv'])) {
                $this->error("上传文件格式必须为.xlsx或.xls或.csv");
            }
            $filename = $_FILES['filename']['tmp_name'];
            include_once(dirname(__FILE__) . '/../../../common/PHPExcel/PHPExcel.php');
            //建立reader对象
            if ('csv' == $ftype) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                //默认字符集
                $PHPReader->setInputEncoding('GBK');
                //默认分隔符
                $PHPReader->setDelimiter(',');
                if(!$PHPReader->canRead($filename)){
                    return array();
                }
            } else {
                $PHPReader = new \PHPExcel_Reader_Excel2007();
                if (!$PHPReader->canRead($filename)) {
                    $PHPReader = new \PHPExcel_Reader_Excel5();
                    if (!$PHPReader->canRead($filename)) {
                        $this->error("读取文件错误");
                        return array();
                    }
                }
            }

            $PHPReader->setReadDataOnly(true);
            $objPHPExcel = $PHPReader->load($filename);
            ob_clean();
            try {
                $sheetData = $objPHPExcel->getActiveSheet()->toArray('', true, true, true);
            } catch (\Exception $e) {
//                $e->getMessage();
                $this->error('请确保打开文件不报错及格式与模板一致');
            }
            dump($sheetData);die;
            unset($sheetData[1], $sheetData[2]);
        }

 

$file = "test.csv";  
$type = strtolower( pathinfo($file, PATHINFO_EXTENSION) );  
$path = __YOUR_FILE_PATH__.'/'.$file;
if (!file_exists($path)) { die('no file!'); }//根据不同类型分别操作

 if( $type=='xlsx'||$type=='xls' ){ 
 		$objPHPExcel = PHPExcel_IOFactory::load($path);
  }else if( $type=='csv' ){ 
  		$objReader = PHPExcel_IOFactory::createReader('CSV')
  		 ->setDelimiter(',')  
  		 ->setInputEncoding('GBK') //不设置将导致中文列内容返回boolean(false)或乱码   
  		 ->setEnclosure('"')  
  		 ->setLineEnding("\r\n")  //新版本可删除 
  		 ->setSheetIndex(0); 
		$objPHPExcel = $objReader->load($path); 
}else{ 
		die('Not supported file types!'); 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值