php利用phpexcel地excel文件进行读取

function actionExcel() {
        $file = \Yii::$app->assetManager->basePath . DIRECTORY_SEPARATOR . "test.xls";
        dump($file);
        //根据不同类型分别操作
        $type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($type == 'xlsx' || $type == 'xls') {
            $objPHPExcel = \PHPExcel_IOFactory::load($file);
        } else if ($type == 'csv') {
            $objReader = \PHPExcel_IOFactory::createReader('CSV')
                ->setDelimiter(',')
                ->setInputEncoding('GBK')//不设置将导致中文列内容返回boolean(false)或乱码
                ->setEnclosure('"')
                ->setSheetIndex(0);
            $objPHPExcel = $objReader->load($file);
        }
        $sheet = $objPHPExcel->getSheet(0);//第一个表格
        $highestRowNum = $sheet->getHighestRow();//
        $highestColumn = $sheet->getHighestColumn();
        $highestColumn = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $filed = [];
        for ($i = 0; $i < $highestColumn; $i++) {
            $cellName = \PHPExcel_Cell::stringFromColumnIndex($i) . '1';
            $value = $sheet->getCell($cellName)->getValue();
            $filed[] = $value;
        }
        $data = array();
        for ($i = 2; $i <= $highestRowNum; $i++) {//ignore row 1
            $row = array();
            for ($j = 0; $j < $highestColumn; $j++) {
                $cellName = \PHPExcel_Cell::stringFromColumnIndex($j) . $i;
                $cellVal = $sheet->getCell($cellName)->getValue();
                $row[$filed[$j]] = $cellVal;
            }
            $data [] = $row;
        }
        dump($data);
    }

  

支持linux、windows平台运行,无需安装office组件。

posted @ 2017-05-10 15:15  lobtao  阅读(124)  评论(0)    收藏  举报