Excel上传

    /**
     * 本地上传
     * 上传excel文件并获取数据
     */
    public function uploadExcel()
    {
        $file = request()->file('file');
        if (empty($file)) {
            $this->error('文件不能为空');
        }
        $dirName = 'user_plan_excel';
        $mSize = 2;
        $info = $file->validate(['size'=>1024*1024*$mSize,'ext'=>'xls,xlsx'])
            ->rule("uniqid")->move(ROOT_PATH . "public/uploads/$dirName");
        if (empty($info)) {
            $this->error('上传文件失败');
        }
        $fileName = $info->getFilename();
        $filePath = $info->getPath().DS.$fileName;
        $res = $this->read_excel($filePath);
        unset($info);
        unlink($filePath);//删除excel文件
        if ($res['code'] != 200) {
            $this->result($res['msg'], [], $res['code']);
        }

        $this->success('success', ['data' => $res['data']]);
    }

    /**
     * 读取excel
     * @param $re_path
     * @return array
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    function read_excel($re_path)
    {
        if (!file_exists($re_path)) {
            $res["code"] = 500;
            $res["msg"] = "文件不存在";
            return $res;
        }
        $obj_reader = \PHPExcel_IOFactory::createReaderForFile($re_path);
        $obj_reader->setReadDataOnly(true); //使用文件流读取文件
        $obj_excel = $obj_reader->load($re_path, $encode = "utf-8");
        if (!$obj_excel) {
            $res["code"] = 500;
            $res["msg"] = "文件读取失败";
            return $res;
        }

        //取数据
        $excel_array = $obj_excel->getSheet(0)->toArray();
        $retData = [];
        foreach ($excel_array as $key=>$item) {
            if ($key == 0){
                continue;
            }
            $retData[$key-1] = (int)$item[0];
        }

        // PHPExcel对象销毁
        $obj_excel->disconnectWorksheets();
        unset($obj_excel);
        unset($obj_reader);
        $res["code"] = 200;
        $res["msg"] = "文件成功";
        $res["data"] = $retData;
        return $res;
    }
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值