使用PHPExcel进行判断excel的类型并导入Demo

  •   
  • 5492
  • PHP
  • 33
  • super_dodo
  • 2017/04/18

最近遇到一个小功能,需要对远程的Excel进行读取并执行任务导入到数据库里面。这个时候就需要判断Excel是2003还是2007版本了。虽然大多数都可以根据文件名进行判断,但是PHPExcel提供了更加完善的方法。PHPExcel_IOFactory::identify($excelFile); //'Excel5' 'Excel2007'得到的excel的地址。

读取远程文件到本地可以直接使用ile_put_contents($excelFile,file_get_contents($file_url)); //下载到本地,亦可wget方式

//使用Excel批量导入数据 file_url 是远程阿里云Oss上面的
public static function importByExcel($file_url){
    //file_url是远程的文件地址,需要先抓取下来才能读取
//    $file_url = 'http://****-hangzhou.aliyuncs.com/uploader/14493_xlsx.xlsx';

    //远程读取数据
    $excelPath = Yii::$app->basePath.'/runtime/';       //本地临时目录
    $excelFile = $excelPath.'.xlsx';                    //TODO 兼容更多的格式
    file_put_contents($excelFile,file_get_contents($file_url));     //下载到本地 wget

    $excelType = \PHPExcel_IOFactory::identify($excelFile); //'Excel5' 'Excel2007'
    $phpExcel = new \PHPExcel;
    $excelReader = \PHPExcel_IOFactory::createReader($excelType);
    $phpExcel = $excelReader->load($excelFile)->getSheet(0);//载入文件并获取第一个sheet
    $total_line = $phpExcel->getHighestRow();            //多少行
    $total_column = $phpExcel->getHighestColumn();       //多少列

    $map = ['name','url','desc'];

    $total_count = 0;       //总的数目
    $fail_count = 0;        //失败的数目
    $fail_reason = [];
    for($row = 5; $row <= $total_line; $row++) {
        $item = array();
        for($column = 'A'; $column <= 'C'; $column++) {
            $item&#91;&#93; = trim($phpExcel->getCell($column.$row)->getValue());
        }
        if($item[0]){       //有产品名字即可
            $total_count += 1;
            //TODO 批量添加
            $mapItem = array_combine($map, $item);  //map为key item为值 合并两个数组
            $model = new Product();
            $model->name = $mapItem['name'];
            $model->url = $mapItem['url'];
            $model->desc = $mapItem['desc'];
            $model->remark = 'Excel导入';
            if(!$model->save()){
                $fail_count += 1;
                $fail_reason[] = ['row'=>$row,'name'=>$mapItem['name'],'msg'=>$model->getFirstErrorMessage()];     //错误的行记录下来
                continue;
            }
        }
    }
    //处理完之后删除临时的excel本地文件
    unlink($excelFile);
    return 1;
}

你不快乐是因为你可以像猪一样懒,却无法像猪一样懒得心安理得。