fastadmin导入excel

在对应控制层加上2个方法import跟readFile,注意需要把对应的方法引入一下

/**
     * 重写import方法
     */
    public function import()
    {
        $file = $this->request->request('file'); //'file'为文件字段名
        $data = $this->readFile($file);
        if (count($data) <= 0) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        /*处理data数据*/
        $nfc_num = 0;//需要投送的NFC数量(总数)
        foreach ($data as $k=>$v){
            $data[$k]['createtime'] = time();
            $data[$k]['admin_id'] = $this->auth->getUserInfo()['id'];
            $data[$k]['type'] = 2;
            $nfc_num += $v['nfc_num'];
        }
        if ($nfc_num <= 0){
            $this->error('NFC数量不能小于0');
 
### FastAdmin 中使用 PhpSpreadsheet 进行循环导入FastAdmin 框架中集成 PhpSpreadsheet 库可以实现 Excel 文件的数据读取与处理功能。为了完成数据的批量导入操作,通常会按照如下方式编写代码: #### 准备工作 首先,在项目根目录下通过 Composer 安装 `phpoffice/phpspreadsheet` 扩展包。 ```bash composer require phpoffice/phpspreadsheet ``` #### 控制器逻辑 创建一个新的控制器方法用于接收上传文件并解析其内容。此部分负责验证请求合法性以及调用具体业务逻辑来执行实际的数据入库动作。 ```php <?php namespace app\controller; use think\Request; use PhpOffice\PhpSpreadsheet\IOFactory; class ImportController extends BaseController { public function importExcel(Request $request){ // 验证是否有文件上传 if ($file = $request->file('excel')) { try{ // 设置临时路径保存上传后的文件 $info = $file->validate(['ext'=>['xlsx','xls']])->move('./uploads/excels'); // 加载文档到 Spreadsheet 对象 $reader = IOFactory::createReaderForFile($info->getSaveName()); $spreadsheet = $reader->load($info->getRealPath()); // 获取活动的工作表 $worksheet = $spreadsheet->getActiveSheet(); $highestRow = $worksheet->getHighestDataRow(); foreach(range(2,$highestRow) as $row){ // 假设首行为标题栏故从第二行开始遍历 $data[]=[ 'field1'=>$worksheet->getCellByColumnAndRow(1,$row)->getValue(), 'field2'=>$worksheet->getCellByColumnAndRow(2,$row)->getValue(), ... // 继续获取其他字段... ]; } // 调用模型层函数将数组中的记录逐条写入数据库 (new YourModel())->saveAll($data); return json(['status'=>true,'msg'=>'Import successful']); }catch(\Exception $e){ return json(['status'=>false,'error'=>$e->getMessage()]); } }else{ return json(['status'=>false,'error'=>"No file uploaded"]); } } } ``` 上述代码片段展示了如何利用 PhpSpreadsheet 的 API 来打开指定格式的电子表格文件,并从中提取有用的信息存放到 PHP 数组内以便后续存储至 MySQL 数据库中[^1]。 请注意安全性和性能优化方面的问题,比如应该考虑设置合理的最大允许导入行数限制、防止 SQL 注入攻击等措施[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值