老莫的笔记本  
  
查看: 968|回复: 0

Laravel 新 excel 导入方法

[复制链接]

662

主题

878

帖子

5145

积分

超级版主

Rank: 8Rank: 8

积分
5145
发表于 2020-12-25 14:17:09 | 显示全部楼层 |阅读模式
本帖最后由 周大胖子 于 2020-12-25 16:19 编辑

使用组件  maatwebsite/Excel 3.1
  1. composer require maatwebsite/excel
复制代码

安装完成后,搞一个 Import文件[我理解这玩意的意思是导入模型]
  1. php artisan make:import CmsTrademarksImport --model=app\model\ CmsTrademarks
复制代码



参考文献:https://learnku.com/articles/32400  [说实话,这篇文章,怎么说呢, 嗯 乱七八糟]

本胖重新总结了一份:

      首先 就是控制器的文件,接收、存储、调用的问题 [ 这个统一复制就好 ]
     一:引入乱七八糟的文件[这是 控制器 ]
  1. namespace App\Http\Controllers\Out;

  2. use Illuminate\Routing\Controller as BaseController;

  3. use Illuminate\Http\Request;

  4. use Illuminate\Support\Facades\Input;

  5. use Illuminate\Support\Facades\Storage;

  6. use App\Model\CmsSellTrademark;


  7. use PhpOffice\PhpSpreadsheet\Settings;

  8. use DB;

  9. // 导入模型
  10. use App\Imports\CmsSellTrademarkImport;
  11. // Imports
  12. use Maatwebsite\Excel\Concerns\ToArray;

  13. use Maatwebsite\Excel\Facades\Excel;
复制代码
    二 接收判断文件,并调用import 【我觉得可以叫他导入模型】
  1. public function import(Request $request)
  2.     {
  3.         // dd(1);

  4.         if (!$request->hasFile('file')) {
  5.             return [
  6.                 'code' => 1,
  7.                 'message' => '友情提示:未检索到上传文件'
  8.             ];
  9.         }
  10.       
  11.         $file = $request->file('file');
  12.         
  13.         // 保存随机
  14.         $file->getClientSize();
  15.       
  16.         //扩展名
  17.         $ext = $file->getClientOriginalExtension();
  18.      
  19.         // 这段代码是用来处理导入时报的一个读取XML过大的错误
  20.         Settings::setLibXmlLoaderOptions(LIBXML_COMPACT | LIBXML_PARSEHUGE);

  21.         // 设置内存无限制
  22.         ini_set('memory_limit', -1);

  23.         $newName = 'shop'.date('Y-m-d').time().'.'.$ext;
  24.         // 存放到本地
  25.         $path=$file->move('./uploads/excel/', $newName);

  26.         $filePath = './uploads/excel/'.$newName;
  27.        // dd( $filePath );

  28.         $data = Excel::import(new CmsSellTrademarkImport,  $filePath);
  29.    
  30.         return [
  31.             'code' => 0,
  32.             'message' => '导入成功' ,
  33.             'data' =>$data
  34.         ];

  35.     }
复制代码
  其实,即使没存进去,也会自动判断存储成功的,呵呵 。 没办法,没返回值 我不得搞个返回结果嘛-.-


好了,上面复制完了,下面开始看个人需求[ 第一种适合单个 sheet 导入;  第二种适合多个sheet 导入 ]
      导入之前,先明白   DB::table('数据库名')->insert($Json); 其实是个可以批量导入的语言,如果 $json 是个数组,他就是插入批量数据,是个json 那就只插入一条数据


第一种:【单个版】文件:App\Imports\CmsSellTrademarkImport.php
  1. <?php

  2. namespace App\Imports;
  3.             //   Imports

  4. use App\Model\CmsSellTrademark;
  5. use Illuminate\Support\Facades\Hash;
  6. use Maatwebsite\Excel\Concerns\ToModel;
  7. use Illuminate\Support\Collection;
  8. use Maatwebsite\Excel\Concerns\ToArray;
  9. use Maatwebsite\Excel\Concerns\ToCollection;
  10. use Maatwebsite\Excel\Concerns\WithMultipleSheets;
  11. use App\Imports\FirstSheetImport;
  12. use DB;

  13. class CmsSellTrademarkImport implements WithMultipleSheets
  14. {


  15.   /**
  16.     * @param Collection $collection
  17.     */
  18.     public function collection(Collection $rows)
  19.     {
  20.         
  21.         //如果需要去除表头
  22.         unset($rows[0]);

  23.         //$rows 是数组格式
  24.         $this->createData($rows);
  25.     }


  26.         // public function ToCollection(Collection $rows)
  27. //    {
  28. //        //如果需要去除表头
  29. //        unset($rows[0]);
  30. //        //$rows 是数组格式
  31. //        $this->createData($rows);
  32. //    }

  33.     // 存储
  34.     public function createData($rows)
  35.     {

  36.             $allJson =array();
  37.          // dd($rows);
  38.            
  39.             foreach ($rows as $k => $v) {
  40.                     // 由于部分sheet 页有大量空行,所以加入判断跳出循环
  41.                     if(empty($v[0])){
  42.                              break;
  43.                     }
  44.                     $allJson[] = $this->addJson($v);
  45.             }
  46.         // dd($allJson);
  47.         DB::table('cms_sell_trademark')->insert($allJson);
  48.     }

  49.     // 拼一个json
  50.     public  function addJson($row){
  51.             $stateCurrentArr = config('xufengcode.stateCurrentArr');
  52.         $tradeCodeArr = config('xufengcode.tradeCodeArr');

  53.         if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $row[4])) {
  54.             $row[4] = $row[4];
  55.         } else {
  56.             $row[4] = null;
  57.         }

  58.         $row[7] = array_search( $row[7], $stateCurrentArr);
  59.         $row[8] = array_search( $row[8], $tradeCodeArr);

  60.         if(empty($row[9])){
  61.             $row[9] = '';
  62.         }
  63.             $a = array(
  64.                     'ctype'                     => $row[0],
  65.                    'tmNumberText'            => $row[1],
  66.                    'tmNameText'            => $row[2],
  67.                    'registerDate'            => $row[4],
  68.                    'tmGoodsName'            => $row[5],
  69.                    'likegroup'                    => $row[6],
  70.                    'stateCurrent'            => $row[7],
  71.                    'tradeCode'                    => $row[8],
  72.                    'remarks'                    => $row[9]
  73.             );
  74.             return $a;
  75.     }
  76.   }
复制代码




第二个 [多 sheet版] 其实这个版本,有两个导入模型,
   第一个文件:App\Imports\CmsSellTrademarkImport.php
  1. <?php

  2. namespace App\Imports;
  3.             //   Imports

  4. use App\Model\CmsSellTrademark;
  5. use Illuminate\Support\Facades\Hash;
  6. use Maatwebsite\Excel\Concerns\ToModel;
  7. use Illuminate\Support\Collection;
  8. use Maatwebsite\Excel\Concerns\ToArray;
  9. use Maatwebsite\Excel\Concerns\ToCollection;
  10. use Maatwebsite\Excel\Concerns\WithMultipleSheets;
  11. use App\Imports\FirstSheetImport;
  12. use DB;

  13. class CmsSellTrademarkImport implements WithMultipleSheets
  14. {
  15.    
  16.    

  17.     // 获取分页数据
  18.     public function sheets(): array
  19.         {
  20.             $sheet = [];
  21.             for ($i=0; $i<=44; $i++) {
  22.                 $sheet[$i] = new FirstSheetImport();
  23.             }
  24.             return $sheet;
  25.         }




  26. }
复制代码
第二个:App\Imports\FirstSheetImport.php [ 名字随意 ]
  1. <?php

  2. namespace App\Imports;  

  3. use App\Model\CmsSellTrademark;
  4. use Illuminate\Support\Facades\Hash;
  5. use Maatwebsite\Excel\Concerns\ToModel;
  6. use Illuminate\Support\Collection;
  7. use Maatwebsite\Excel\Concerns\ToArray;
  8. use Maatwebsite\Excel\Concerns\ToCollection;
  9. use Maatwebsite\Excel\Concerns\WithMultipleSheets;
  10. use DB;

  11. class FirstSheetImport implements ToCollection
  12. {
  13.    /**
  14.     * @param Collection $collection
  15.     */
  16.     public function collection(Collection $rows)
  17.     {
  18.         
  19.         //如果需要去除表头
  20.         unset($rows[0]);

  21.         //$rows 是数组格式
  22.         $this->createData($rows);
  23.     }

  24.     // 存储
  25.     public function createData($rows)
  26.     {

  27.             $allJson =array();
  28.          // dd($rows);
  29.            
  30.             foreach ($rows as $k => $v) {
  31.                     // 由于部分sheet 页有大量空行,所以加入判断跳出循环
  32.                     if(empty($v[0])){
  33.                              break;
  34.                     }
  35.                     $allJson[] = $this->addJson($v);
  36.             }
  37.         // dd($allJson);
  38.         DB::table('cms_sell_trademark')->insert($allJson);
  39.     }

  40.     // 拼一个json
  41.     public  function addJson($row){
  42.             $stateCurrentArr = config('xufengcode.stateCurrentArr');
  43.         $tradeCodeArr = config('xufengcode.tradeCodeArr');

  44.         if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $row[4])) {
  45.             $row[4] = $row[4];
  46.         } else {
  47.             $row[4] = null;
  48.         }

  49.         $row[7] = array_search( $row[7], $stateCurrentArr);
  50.         $row[8] = array_search( $row[8], $tradeCodeArr);

  51.         if(empty($row[9])){
  52.             $row[9] = '';
  53.         }
  54.             $a = array(
  55.                     'ctype'                     => $row[0],
  56.                    'tmNumberText'            => $row[1],
  57.                    'tmNameText'            => $row[2],
  58.                    'registerDate'            => $row[4],
  59.                    'tmGoodsName'            => $row[5],
  60.                    'likegroup'                    => $row[6],
  61.                    'stateCurrent'            => $row[7],
  62.                    'tradeCode'                    => $row[8],
  63.                    'remarks'                    => $row[9]
  64.             );
  65.             return $a;
  66.     }

  67. }
复制代码









回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表