Thinkphp6利用反射机制进行动态Execl文件数据保存到不同数据表中

问题描述:当导入Excel模板文件时,可以根据需要上传的文件种类灵活存储在不同的数据表中

解决思路:

  1. 首先先引入处理Excel需要的文件
composer require phpoffice/phpspreadsheet
  1. 直接上代码,uploadExcel1为生成读取后的结果数组,uploadExcel2为利用反射机制,根据传递的参数,通过对应模型的save方法动态保存到相应的表中
<?php


namespace app\service;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Request;
class ExcelService
{

    /**
     * @param Request $request
     * @param string $fileParamName  对应表单的name属性
     * @param array $keys            数据表的字段名称
     * @param int $startRow          起始行数
     * @param int $startCol          起始列数
     * @param string $uploadUser     上传者
     * @return array                 返回结果数组
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function uploadExcel1(Request $request, string $fileParamName, array $keys, int $startRow = 2, int $startCol = 1, string $uploadUser = 'user')
    {
        $finalArray = array();

//        获取文件地址
        $file = $request->file($fileParamName)->getRealPath();
        $inputFileType = IOFactory::identify($file);//获取Excel后缀  xls / xlsx /csv
        //获取Excel文件
        $reader = IOFactory::createReader($inputFileType);
//        加载文件
        $spreadsheet = $reader->load($file);
        //读取表格
        $sheet = $spreadsheet->getActiveSheet();
        //获取列
        $highestColumn = $sheet->getHighestColumn();
        //获取总行数
        $highestRow = $sheet->getHighestRow();
//        获取真实有效的行数
        $realHighestRow = null;
        for ($i = $highestRow; $i > $startRow -1 ; $i--) {
            if($sheet->getCellByColumnAndRow(3,$i)->getValue()){
                $realHighestRow = $i;
                break;
            }
        }
        //将列数字母转化为数字:A->1
        $highestColumn = Coordinate::columnIndexFromString($highestColumn);

        for ($i = $startRow; $i <= $realHighestRow; $i++) {
            //获取每行数据的的有效列数
            $realCol = count($keys)+$startCol-1;
            $tpl = array();
            for($j = $startCol; $j<=$realCol; $j++){
                $tpl[$keys[$j-$startCol]] = $sheet->getCellByColumnAndRow($j, $i)->getValue();
            }
            $tpl['upload_user'] = $uploadUser;
            $finalArray[] = $tpl;
        }
        return $finalArray;
    }


    /**
     * @param Request $request
     * @param string $fileParamName  对应表单的name属性
     * @param array $keys            数据表的字段名称
     * @param int $startRow          起始行数
     * @param int $startCol          起始列数
     * @param string $uploadUser     上传者
     * @param string $modelName      反射的模型名称
     * @return int                   成功插入的行数
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \ReflectionException
     */
    public function uploadExcel2(Request $request, string $fileParamName, array $keys, int $startRow = 2, int $startCol = 1, string $uploadUser = 'user', string $modelName)
    {
        $num = 0;

//        获取文件地址
        $file = $request->file($fileParamName)->getRealPath();
        $inputFileType = IOFactory::identify($file);//获取Excel后缀  xls / xlsx /csv
        //获取Excel文件
        $reader = IOFactory::createReader($inputFileType);
//        加载文件
        $spreadsheet = $reader->load($file);
        //读取表格
        $sheet = $spreadsheet->getActiveSheet();
        //获取列
        $highestColumn = $sheet->getHighestColumn();
        //获取总行数
        $highestRow = $sheet->getHighestRow();
//        获取真实有效的行数
        $realHighestRow = null;
        for ($i = $highestRow; $i > $startRow -1 ; $i--) {
            if($sheet->getCellByColumnAndRow(3,$i)->getValue()){
                $realHighestRow = $i;
                break;
            }
        }
        for ($i = $startRow; $i <= $realHighestRow; $i++) {
            //获取每行数据的的有效列数
            $realCol = count($keys)+$startCol-1;
            $tpl = array();
            for($j = $startCol; $j<=$realCol; $j++){
                $tpl[$keys[$j-$startCol]] = $sheet->getCellByColumnAndRow($j, $i)->getValue();
            }
            $tpl['upload_user'] = $uploadUser;

            $model = '\\app\\model\\'.$modelName;
//        反射类
            $reflect = new \ReflectionClass($model);
//        执行构造函数,实现构造函数的依赖注入
            $instance = $reflect->newInstance();
//        执行注入类的方法
            $reflectMethod = $reflect->getMethod('save');
            $res = $reflectMethod->invokeArgs($instance,[$tpl]);
            if($res)
            {
                $num += 1;
            }
        }
        return $num;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值