php csv以及excel文件格式读取数据的处理

本文介绍了如何使用PHP的phpcsv和PHPExcel库读取CSV和Excel文件,包括文件上传、验证、移动,以及针对不同文件类型的Excel和CSV数据处理方法。着重展示了数据解析、编码转换和错误处理的过程。
摘要由CSDN通过智能技术生成

php csv以及excel文件格式读取数据的处理

    /**
     * 上传文件,包含单文件以及批量文件的综合处理
     * @return array|false
     */
    public function upload()
    {
        $filesArr = [];
        $validate = ['ext' => 'xls,xlsx,csv'];
        $move = '../data/runtime/feetempletfiles';
        $files = request()->file('files');
        if (is_object($files)) {//单文件对象处理
            $info = $files->validate($validate)->move($move);
            if ($info) {
                array_push($filesArr, $info);
            } else {
                $this->fileError = $files->getError();
                return false;
            }
        } else {//多文件数组处理
            if (empty($files)) {//非法请求,通过文件请求却未提供文件
                return null;
            } else {
                foreach ($files as $file) {
                    $info = $file->validate($validate)->move($move);
                    if ($info) {
                        array_push($filesArr, $info);
                    } else {
                        $this->fileError = $file->getError();
                        return false;
                    }
                }
            }
        }

        return $filesArr;
    }

    /**
     * 获取文件错误信息
     * @return string
     */
    public function getFileError()
    {
        return $this->fileError;
    }

    /**
     * 文件处理中心
     * @param array|object $files 文件信息
     * @return array|false|mixed|void
     */
    public function handleFiles($files)
    {
        $type = $this->judgeFileForm($files->getExtension());
        if ($type == 'excel') {
            $data = $this->disposeExcel($files);
        } else {//csv
            $data = $this->disposeCsv($files);
        }
        return $data ? $data : false;
    }

    /**
     * 判断文件类型
     * @param string $filesExtension 文件后缀扩展
     * @return string
     */
    public function judgeFileForm(string $filesExtension)
    {
        $filesExtension = strtolower($filesExtension);
        if (in_array($filesExtension, ['xls', 'xlsx'])) {
            return 'excel';
        } else {
            return 'csv';
        }
    }

    /**
     * excel文件处理
     * @param object $fileInfo 文件信息
     * @return array|false
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function disposeExcel(object $fileInfo)
    {
        ini_set('memory_limit', '2048M');

        vendor('phpoffice.phpexcel.Classes.PHPExcel.IOFactory');
        $PHPReader = \PHPEXCEl_IOFactory::createReaderForFile($fileInfo->getPathname());
        $objPHPExcel = $PHPReader->load($fileInfo->getPathname());
        $sheetCount = $objPHPExcel->getSheetCount();
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected);
        $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow();
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
        $data = [];
        for ($row = 1; $row <= $rowCount; $row++) {
            for ($column = 'A'; $column <= $columnCount; $column++) {
                $data[] = $objPHPExcel->getActiveSheet()->getCell($column . $row)->getValue();
            }
        }
        if (empty($data)) {
            return false;
        } else {
            $data = FreightTemplateTransfer::fileInProcessData($data);
            return $data;
        }
    }

    /**
     * csv文件处理
     * @param object $fileInfo 文件信息
     * @return array|false
     */
    public function disposeCsv(object $fileInfo)
    {
        ini_set('memory_limit', '2048M');

        $fopen = fopen($fileInfo->getPathname(), 'r');
        $checkEncoding = '';
        while ($datum = fgetcsv($fopen)) {
            $checkEncoding = empty($checkEncoding) ? $this->checkEncoding($datum[0]) : $checkEncoding;
            foreach ($datum as $key => $v) {
                $data[] = mb_convert_encoding($v, "UTF-8", $checkEncoding);
            }
        }
        fclose($fopen);
        if (empty($data)) {
            return false;
        } else {
            $data = FreightTemplateTransfer::fileInProcessData($data);
            return $data;
        }
    }

    /**
     * manual getcsv
     * @param $handle
     * @param null $length
     * @param string $d
     * @param string $e
     * @return false|mixed
     */
    public function fgetcsvReg(&$handle, $length = null, $d = ',', $e = '"')
    {
        $d = preg_quote($d);
        $e = preg_quote($e);
        $_line = "";
        $eof = false;
        while ($eof != true) {
            $_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
            $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
            if ($itemcnt % 2 == 0)
                $eof = true;
        }
        $_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
        $_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
        preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
        $_csv_data = $_csv_matches[1];
        for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
            $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1', $_csv_data[$_csv_i]);
            $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
        }
        return empty ($_line) ? false : $_csv_data;
    }

    /**
     * 检测编码
     * @param string $str 要检测的字符串
     * @return false|string
     */
    public function checkEncoding($str = "")
    {
        $encodings = [
            'ASCII',
            'UTF-8',
            'GBK'
        ];
        foreach ($encodings as $encoding) {
            if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", $encoding), $encoding, "UTF-32")) {
                return $encoding;
            }
        }
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值