【问题标题】:How to add extra data to collection from maatwebsite/Excel如何从 maatwebsite/Excel 向集合添加额外数据
【发布时间】:2019-09-18 03:48:49
【问题描述】:

我正在使用包maatwebsite/excel v2.1 将用户导入页面。

我已经上传了文件,但我想事先向用户展示他正在导入什么以及哪些行无法导入(因为缺少数据或用户已经存在),但为此我想至少添加 2额外的字段,1 会告诉我该行是否可以上传(审美目的)以及带有文本的订单,告诉他为什么不能导入该行。

我得到这样的文件行

$users = Excel::load($ruta.'/'.$filename, function ($reader) {
})->get();

这会返回这个集合,对于第一个值,用户分配了电子邮件test@subject.com,第二个值是rif 字段格式错误

[
    {
        "email": "test@subject.com",
        "empresa": "business1",
        "encargado": "person1",
        "rif": "J-12345-1",
    },
    {
        "email": "test@subject2.com",
        "empresa": "business2",
        "encargado": "Person 2",
        "rif": "123456-2",

    }
]

我想要添加这样的额外字段

[
    {
        "email": "test@subject.com",
        "empresa": "business1",
        "encargado": "person1",
        "rif": "J-12345-1",
        "validity": 0,
        "reason": "Email is already used"
    },
    {
        "email": "test@subject2.com",
        "empresa": "business2",
        "encargado": "Person 2",
        "rif": "123456-2",
        "validity": 0,
        "reason": "the rif field is badly formatted" 
    }
]

正如我所说,这些字段并不是要保存在文档中,而是为了向用户展示将导入什么、不导入什么以及为什么不导入的图例。

我知道我可以在回调函数中检查我需要的内容,但是如何将这些值插入到集合中?

【问题讨论】:

  • ...进入哪个集合?您能否举例说明您要添加哪些数据以及在何处添加?
  • 按要求编辑

标签: excel laravel file-upload


【解决方案1】:

您可以使用map() 方法来操作所有集合项。

$users = Excel::load($ruta.'/'.$filename, function ($reader) {
})->get();

$newUsers = $users->map(function($user){
return [
        "email" => $user->email,
        "empresa" => $user->empresa,
        "encargado" => $user->encargado,
        "rif" => $user->rif,
        // make your controls and add new items here
        "validity" => $validate,
        "reason" => $reason

    ]
})

但请注意,我们将数组发回。当您尝试在迭代中访问数据时(可能在您看来),您不能说 $user->email,它会抛出 Trying to get property of non-object 所以您应该说 $user["email"] ..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2012-04-29
    相关资源
    最近更新 更多