php 使用maatwebsite/excel 3.1将Excel数据(收集行)导入Laravel 9数据库的问题

nwlls2ji  于 2023-11-16  发布在  PHP
关注(0)|答案(1)|浏览(196)

我试图使用Maatwebsite-excel 3.1从Excel工作表导入多行。这里,是挑战,当我这样做时。dd($row)它打印所有行。然而,当我没有运行没有DD的代码时,它神奇地“清空”行。下面是我的代码

public function collection(Collection $rows)
    {
        $rows->shift();

        $total_amount = 0;
        foreach ($rows as $row){

            if($row->filter()->isNotEmpty()){
                $article_title =collect(trim($row[0]))[0];
                $tag = collect(trim($row[1]))[0];
                $words = collect((int) $row[2])[0];
                $deadline = collect(trim($row[3]))[0];
                $pkw = collect(trim($row[4]))[0];
                $skw1 = collect(trim($row[5]))[0];
                $skw2 = collect(trim($row[6]))[0];
                $instructions = collect(trim($row[7]))[0];
                $my_tag = UserTag::where('name', 'LIKE', '%'.$tag.'%')->first();
                $my_urgency = Urgency::where('name', 'LIKE', '%'.$deadline.'%')->first();
//                dd($tag, $words, $my_urgency);
                $amount  = $my_tag->amount_per_word * $my_urgency->amount * $words;
                $project_deadline = now()->addHours($my_urgency->hours)->format('Y-m-d H:i:s');
                Project::create([
                    'user_id'=>request()->user()->id,
                    'article_title'=>$article_title,
                    'upload_batch_id'=>$this->batch->id,
                    'user_tag_id'=>$my_tag->id,
                    'urgency_id'=>$my_urgency->id,
                    'price_per_word'=>$my_tag->amount_per_word,
                    'no_of_words'=>$words,
                    'deadline'=>$project_deadline,
                    'amount'=>($amount),
                    'primary_keyword'=>$pkw,
                    'secondary_keyword_1'=>$skw1,
                    'secondary_keyword_2'=>$skw2,
                    'instructions' => $instructions
                ]);
                $total_amount = $total_amount + $amount;
            }
        }
        $this->batch->amount = $total_amount;
        $this->batch->update();
    }

字符串
我也用过,没有collect(trim(row[value])),但这也没有工作.
我试过跟随these solutions,但没有一个对我有效。
这里是错误x1c 0d1x
下面是我的DD声明



请好心地帮助我。

new9mtju

new9mtju1#

明白了。将WithHeadingRow实现到类中,然后删除$rows->shift();
这将使第一行数组键。然后你可以访问他们以后:

class ProjectsImport implements ToCollection, WithHeadingRow
{
   public function collection(Collection $rows){
        $total_amount = 0;
        foreach ($rows as $row){

            if($row->filter()->isNotEmpty()){

                $article_title = $row['article_name'];
    }
  }
 }
}

字符串

相关问题