问题
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.
Get csv content before download: \Excel::raw
Convert to another encoding: mb_convert_encoding https://docs.laravel-excel.com/3.1/exports/collection.html#storing-raw-contents
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