1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel ExcelのCSVインポートで、日本語のカラム名を取得できない問題。

Last updated at Posted at 2024-01-29

ヘッダーのカラム名を取得

エンコーディングの問題以前に、そもそもヘッダーの行を正常に取得できていなかった。
以下設定でformatterをnoneにすれば解決する。

config/excel.php
'imports' => [
    'heading_row' => [
        'formatter' => 'none',
    ],
],

クラス毎に設定する場合は以下。

Imports/TestImport.php
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');

class TestImport implements ToModel
{
}

シフトJISの文字化け

先程のconfig/excel.phpでも設定できるが、
クラスに設定する場合は、getCsvSettings()を追記する。
WithCustomeCsvSettingsをimplementsすることも忘れずに。

Imports/TestImport.php
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;

class TestImport implements ToModel, WithHeadingRow, WithCustomCsvSettings
{
    public function model(array $row)
    {
        return new User([
            'name' => $row['名前'],
            'email' => $row['メールアドレス'],
        ]);
    }

    public function getCsvSettings(): array
    {
        return [
            'input_encoding' => 'SHIFT-JIS'
        ];
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?