I am trying to remove all the empty rows from a csv and make it downloadable. In this process, there is no involvement of database/model.
My flow looks like:
- Import csv file.
- Filter empty rows.
- Export the data after all the empty rows are removed.
My code looks like:
#Controller
public function formatCSV()
{
$path = storage_path('app/files/') . 'example.csv';
Excel::import(new FormatCSV, $path);
}
#app/Imports/FormatCSV
<?php
namespace App\Imports;
use App\Exports\ExportFormattedCSV;
use App\Http\Services\AmenityService;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Excel;
class FormatCSV implements ToArray, WithChunkReading
{
private $table,$service,$model;
public function __construct()
{
$this->service = new AmenityService();
}
public function array(Array $rows)
{ $rec_arr = array();
foreach ($rows as $row)
{
$rec_arr[] = array_values($row);
}
$records_arr = $this->service->trimArray($rec_arr);
$export = new ExportFormattedCSV($records_arr);
//print_r($export);
return Excel::download($export, 'csv.csv');
}
public function chunkSize(): int
{
return 10;
}
}
#app/Exports/ExportFormattedCSV
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromArray;
class ExportFormattedCSV implements FromArray
{
protected $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function array(): array
{
return $this->data;
}
}
With this code it does nothing, shows blank at the end.
However, if I uncomment the line print_r($export)
It shows data as:
App\Exports\ExportFormattedCSV Object
(
[data:protected] => Array
(
[0] => Array
(
[0] => First Name
[1] => Last Name
[2] => Roll No
)
[1] => Array
(
[0] => Ram
[1] => Patel
[2] => 1
)
[2] => Array
(
[0] => Rajuv
[1] => Roy
[2] => 2
)
[3] => Array
(
[0] => Sunny
[1] => Deol
[2] => 5
)
[4] => Array
(
[0] => Akshya
[1] => Kumar
[2] => 6
)
[5] => Array
(
[0] => Amir Khan
[1] => 7
[2] =>
)
[6] => Array
(
[0] => Salman
[1] => Khan
[2] => 9
)
[7] => Array
(
[0] => Bobby
[1] => Deol
[2] => 10
)
)
)
The File I am testing is example.csv
First Name,Last Name, Roll No
Ram,Patel,1
Rajuv,Roy,2
,,
Sunny,Deol,5
Akshya,Kumar,6
Amir Khan,7
,,
Salman,Khan,9
Bobby,Deol,10,
Barun,Dhawan,11
,,
Virat,Kohli,13
Rohit,Sharma,14
And trimArray function :
public function trimArray($arr)
{
$final = array();
foreach($arr as $k => $v)
{
if(array_filter($v)) {
$final[] = $v;
}
}
return $final;
}