How to export csv file with shift-jis encoding in laravel?

偶尔善良 提交于 2021-01-28 11:11:02

问题


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.


回答1:


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);



来源:https://stackoverflow.com/questions/60292152/how-to-export-csv-file-with-shift-jis-encoding-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!