Thanh Nguyen
Thanh Nguyen

Reputation: 410

How can I set encoding for export csv with Laravel Excel in Laravel

I using Laravel Excel for export CSV file in Laravel. How can I set the encoding for export csv file.

I have tried several ways:

  1. Change config in excel.php

    'use_bom' => false,
    
  2. Use mb_convert_encoding to convert content to before export.

    $exportData = mb_convert_encoding($exportData, "SJIS", "UTF-8");  
    $pblClassExport = new \App\Exports\PblClassExport($exportData, 'test.csv');
    

But it's not working. The encoding of csv file auto change by file content.

Upvotes: 0

Views: 9265

Answers (3)

4b0
4b0

Reputation: 22323

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

Note: Solution povided by OP on question section.

Upvotes: 0

Hasan
Hasan

Reputation: 63

If you you use Laravel Excel 3.1, you can use WithCustomCsvSettings interface. Then you add your encoding setting in the getCsvSettings method like the following.

use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
class InvoicesExport implements WithCustomCsvSettings
{
   public function getCsvSettings(): array
   {
        return [
            'output_encoding' => 'SJIS',
         ];

    }
}

Plese refer to the docs for more details.

Upvotes: 0

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

you need to configure your PblClassExport.php headers

in PblClassExport.php


/**
 * Optional headers
*/
private $headers = [
    'Content-Type' => 'text/csv',
    'Content-Encoding'=> 'SHIFT-JIS' // somthing like this ?
];

i have't done this but i think it will work

ref link

https://docs.laravel-excel.com/3.1/exports/exportables.html#exportables


Update

you can encode line by line

public function bindValue(Cell $cell, $value)
{
    $value = mb_convert_encoding($value, "SJIS");
    return parent::bindValue($cell, $value);
}

ref link https://www.gitmemory.com/issue/Maatwebsite/Laravel-Excel/1886/552849170

Upvotes: 1

Related Questions