2

I am using laravel-excel to export csv file. To export, the code is like below,

 return Excel::download(new Export(results,$header), "test.csv");

And the Export.php file is like,

namespace App\AllClass;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;

class Export implements FromCollection,WithHeadings
{
    private $myArray;
    private $header;

    public function __construct($myArray,$header){
        $this->myArray = $myArray;
        $this->header = $header;
    }

    public function collection()
    {
        $data = mb_convert_encoding($this->myArray,"SJIS", "UTF-8");
        // dump($data);
        return collect($data);
    }


    public function headings(): array
    {
        $header = mb_convert_encoding($this->header,"SJIS", "UTF-8");
        // dump($header);
        return $header;
    }
}

As you can see, I am converting the data before creating excel. Without converting I can export perfectly in UTF-8 format. But after converting to shift-jis, it is deleting all Japanese character. However, if I dump the header before returning, it is showing me gibberish data; not empty string like the csv file.

Nabil Farhan
  • 1,444
  • 3
  • 25
  • 41

2 Answers2

3

I resolved it.
Let's me share my solution here.
Laravel Excel not support it by default. But we can do it by simple way.

  1. Get csv content before download: \Excel::raw

  2. Convert to another encoding: mb_convert_encoding https://docs.laravel-excel.com/3.1/exports/collection.html#storing-raw-contents

  3. Download csv.

    $exportedObject= new \App\Exports\ClassExport($exportDataArray, $fileName);
    $csvContent = \Excel::raw($exportedObject, $exportedObject->writerType);

    $csvContent = mb_convert_encoding($csvContent, 'SJIS', 'auto');

    // In my case, I upload my csv to S3. $storageInstance = \Storage::disk('s3_import_csvs');
    $putFileOnStorage = $storageInstance->put($fileName, $csvContent);

Thanh Nguyen
  • 390
  • 4
  • 6
0

In config/excel.php, you should change CSV Settings

'use_bom'                => true,

It's work well in Japanese

bravohex
  • 966
  • 13
  • 21