【问题标题】:getting trouble to manage file data after importing the excel file in laravel 5.8在 laravel 5.8 中导入 excel 文件后无法管理文件数据
【发布时间】:2020-01-04 10:11:26
【问题描述】:

我想通过导入excel 文件一次发送多封电子邮件。现在,我正在导入excel 文件并将数据作为数组保存到variable 中。 我正在使用maatwebsite/excel version 3.1。导入后,文件数据作为嵌套数组存储到变量中,excel 文件的其余列也保持空值。我尝试使用array_filter,但它不能正常工作。这是我现在得到的回复截图 - response in console .

在 EmailsController 中 -

public function sendEmailUsingFileAndSave(Request $request)
{
    //here is $content, $fromemail, $fromname etc..

    $file = $request->file('file');

    $import = new EmailsImport;
    Excel::import($import, $file);
    return $emails = $import->data;
    foreach($emails as $email)
    {
        Mail::send('email.content', ['content' => $content], function($message)
             use ($email, $subject, $fromemail, $fromname) {
                  $message->to($email)->subject($subject);
                  $message->from($fromemail, $fromname);
             });
     }
}

app\imports 文件夹中EmailsImport.php 是-

<?php

namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

class EmailsImport implements ToCollection, WithValidation 
{
    use Importable;

    public $data;

    public function collection(Collection $rows)
    {
        $this->data = $rows;
    }
 }

我期待这样的回应 - (2) ["abc@example.com","xyz@example.com", "abc@another.com"]

我的导入示例 excel 文件是 - sample excel file

我一直在尝试这样做,有人可以帮我解决这个问题吗?

【问题讨论】:

  • 看看this 线程。也许您的目标是进行验证

标签: php arrays laravel vue.js laravel-excel


【解决方案1】:

所以你的问题是过滤部分?

然后添加以下代码:

Excel::import($import, $file);

$emails = [];
foreach ($import->data as $item) {
  $item = array_filter($item, function($value) { return !is_null($value) && $value !== ''; });
  foreach ($item as $i) {
    $emails[] = $i;
  }
}

foreach($emails as $email)

【讨论】:

    【解决方案2】:

    您的问题是 Maatwebsite\Excel 将您的 excel 文件中的一些空单元格视为行的一部分,因此当您使用 ToCollection 界面并将 $this-&gt;data 设置为等于 $rows 您正在分配一个二维数组到$this-&gt;data

    有很多方法可以解决这个问题,但我建议在 $rows 集合上使用 foreach 循环,并仅将每行的第一个单元格添加到 $this-data,尝试类似的方法:

    class EmailsImport implements ToCollection, WithValidation 
    {
        use Importable;
    
        public $data = [];
    
        public function collection(Collection $rows)
        {
            foreach ($rows as $row) {
                $this->data[] = $row[0];
            }
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 2021-06-23
      • 1970-01-01
      • 2021-01-02
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多