栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

2021-10-12

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-12

phpspreadsheet实现上传数据转换为数据
  最近公司要开发一个一键导入功能,将Excel文件直接导入到数据库,经过大佬指导终于是成功完成,现记录供日后阅读方便。
  思路:先上传excel文件到服务器,然后利用phpspreadsheet库循环读取表格内容,将数据转换成数组,再写入到数据库。

1.thinkphp5.0利用phpspreadsheet库实现excel文件上传装换为数组,第一步引入phpspreadsheet,通过composer引入phpspreadsheet。
phpspreadsheet文档地址请查看:https://phpspreadsheet.readthedocs.io/en/latest/

composer require phpoffice/phpspreadsheet

2.这里我们使用IOFactory类来读取表格,IOFactory类可以自动是被表格的类型然后加载,具体的实现代码如下

  
    public function oneSend()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . 'public' . $file;
        //判断文件是否存在
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //判断类型
        $ext = IOFactory::identify($filePath);
        //创建读取器,自动获取文件类型
        $reader = IOFactory::createReaderForFile($filePath);
        //类型过滤
        if (!in_array($ext, ['Xls', 'Xlsx', 'Html'])) {
            $this->error(__('Unknown data format'));
        }
        //excel由html构成的文件
        if ($ext === 'Html') {
            $htmlStr = $reader->getSecurityScanner()->scanFile($filePath);
            $htmlStr = preg_replace('/.*/', "", $htmlStr);
            $PHPExcel = $reader->loadFromString($htmlStr);
        } else {
            
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号abc的字母
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $highestColumnIndex = Coordinate::columnIndexFromString($allColumn);  //将列数转化为数字;
//        //第一个是列第二参是行
//        return $PHPExcel->getActiveSheet()->getCellByColumnAndRow(1,1)->getValue();

        $data = [];
        for ($i = 1; $i <= $highestColumnIndex; $i++) {
            for ($a = 2; $a <= $allRow; $a++) {
                $data[$PHPExcel->getActiveSheet()->getCellByColumnAndRow($i, 1)->getValue()][] = $PHPExcel->getActiveSheet()->getCellByColumnAndRow($i, $a)->getValue();
            }
        }
        return  json($data);  //最终转化为数据
    }

3.需要注意的地方是:windows上文件路径是用“”,linux上是“/”,有时候会因为斜杆的问题导致,文件读取不到。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/320692.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号