laravel-excel使用3(老猫包子店的故事)

突然有一天,我的包子铺的员工对我有所不满,于是动手把我的excel表格的一些金额改成了负数,日期也被动了手脚,那肯定不行啊,当务之急就是找出这些负数的金额和这些奇怪的日期,我们姑且称之为坏账吧。

于是我在我的AccountImport中加入了两条验证规则,由于老猫的英语不太好,于是不得不加入些中文提示来告诉我。这时我是这样做的。

<?php

namespace App\Imports;


use App\Models\Account;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\RemembersRowNumber;
use Maatwebsite\Excel\Concerns\WithValidation;


class AccountImport implements ToModel,WithBatchInserts,WithChunkReading, WithValidation
{
    use RemembersRowNumber;
    /**
     * @param array $row
     *
     * @return Account|null
     */
    public function model(array $row)
    {
        $currentRowNumber = $this->getRowNumber();
        echo $currentRowNumber."\r\n";
        if (!is_numeric($row[1])) {
            return null;
        }

        return new Account([
            'date'     => $row[0],
            'money'    => $row[1],
        ]);
    }


    public function batchSize(): int
    {
        return 1000;
    }

    public function chunkSize(): int
    {
        return 50;
    }

    public function rules(): array
    {
        return [
            '0' => 'date',
            '1' => 'min:0',

        ];
    }

    public function customValidationMessages()
    {
        return [
            '0.date' => '必须是日期格式',
            '1.min'  => '必须是大于0的金额'
        ];
    }
}

我尝试运行一下,发现果然有异常抛出 ValidationException,于是我们在导入的地方也需要相应地做些改造,以保证正常。 ExcelRead.php

<?php

namespace App\Console\Commands;

use App\Imports\AccountImport;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Validators\ValidationException;


class ExcelRead extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:ExcelRead';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '操作excel';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try{
            Excel::import(new AccountImport(), public_path('test.xlsx'));
        }catch( ValidationException $e){
            var_dump($e->failures());
//            foreach ($failures as $failure) {
//                $failure->row(); // row that went wrong
//                $failure->attribute(); // either heading key (if using heading row concern) or column index
//                $failure->errors(); // Actual error messages from Laravel validator
//                $failure->values(); // The values of the row that has failed.
//            }
        }

    }
}

说完了导入的所有问题之后,我们下次来介绍下导出会遇到的各种问题以及怎么去使用它的导出功能。老猫的包子铺会火吗?尽情期待。如果你在使用过程中有任何问题,欢迎留言和我一起探讨。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Laravel Excel是一个在Laravel 5中使用的库,它提供了导入和导出Excel/CSV文件的功能。通过使用Laravel Excel,你可以轻松地读取和写入Excel文件,并且可以方便地处理数据。 要在Laravel 5中使用Laravel Excel,你可以按照以下步骤进行操作: 1. 首先,你需要使用Composer来安装Laravel Excel。可以使用以下命令在你的Laravel项目中安装Laravel Excel: ``` composer require maatwebsite/excel ``` 2. 安装完成后,在config/app.php文件中的providers数组中添加以下内容: ``` Maatwebsite\Excel\ExcelServiceProvider::class, ``` 还需要在aliases数组中添加以下内容: ``` 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ``` 3. 接下来,你可以创建一个控制器来处理Excel文件的导入和导出逻辑。在控制器中,你可以使用Laravel Excel提供的一些方法来读取和写入Excel文件。以下是一些示例代码: ```php use Excel; // 导出Excel文件 public function export() { $data = [ ['Name', 'Email'], ['John Doe', 'john@example.com'], ['Jane Smith', 'jane@example.com'], ]; return Excel::download(function($excel) use ($data) { $excel->setTitle('Users'); $excel->sheet('Sheet 1', function($sheet) use ($data) { $sheet->fromArray($data, null, 'A1', false, false); }); }, 'users.xlsx'); } // 导入Excel文件 public function import(Request $request) { $file = $request->file('file'); Excel::import(function($excel) { $excel->sheet(0, function($sheet) { $data = $sheet->toArray(); // 处理导入的数据 foreach($data as $row) { // ... } }); }, $file); } ``` 通过这些代码示例,你可以在Laravel使用Laravel Excel来实现Excel/CSV文件的导入和导出功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Laravel 5使用Laravel Excel实现Excel/CSV文件导入导出的功能详解](https://download.csdn.net/download/weixin_38617196/12962745)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [laravel-excel使用老猫包子故事)](https://blog.csdn.net/qq_39071185/article/details/122015370)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值