1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【LaravelExcel】LaravelExcelのバージョンアップでハマったことまとめ

Last updated at Posted at 2020-12-07

経緯

Laravelをバージョンアップするに伴い、PHPやライブラリであるLaravelExcelやPHPExcelなどもバージョンアップされ、いくつかの変更点でハマった点をまとめてみた

新旧のバージョン情報

Laravel

新:6.18.42
旧:5.1.46

PHP

新:7.4.11
旧:5.6.30

ハマった点と解決方法

Excel::load()の廃止

元々はこんな感じでExcelを読み込んでいました。

test.php
Excel::load('file.xlsx', function ($file) {
  // PHPExcelを使った処理 など
});

→後述のPHPSpreadsheetの機能で読み込む方法に変更しました。
多分、Excelファイルを読み込んで値を返すだけならLaravelExcelの3以降だとExcel::import()を使用するのがいいと思います。
PHPExcelなどを使ってシート、列、行、セルなどを操作している場合はPHPSpreadsheetを使用する形へ変更した方がいいと思います。

PHPExcelの廃止→PHPSpreadsheetへ移行

PHPExcel自体が非推奨・廃止となり、PHPSpreadsheetの使用を推奨されています。
使用するクラスなどが変更となっています。

ちなみにExcelファイルの読み込みは下記のような形で実装しました。


namespace App\Http\Controllers;

use PhpOffice\PhpSpreadsheet\Reader\Xlsx as Reader;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class ImportExcelController extends Controller
{

// エクセル読み込み処理
$reader = new Reader();
$sheet = $reader->load('/test.xlsx');

}

※前述した通り、色々な操作をする場合のExcel::import()での読み込みが上手く構築出来ず…もし何か良い方法などをご存知の方がいらっしゃいましたらご教示くださいますと嬉しいです。

セルオブジェクトの値取得時、列番号の指定が変更

PHPSpreadsheetへ移行したことでセルオブジェクトにおける列番号の指定が変更になりました。これが地味に混乱させる要因に…

旧処理

test.php
$col = 0; // 列
$row = 0; // 行

// A1のセルオブジェクトを取得
$cell = $sheet->getCellByColumnAndRow($col, $row)->getValue();

新処理

test.php
$col = 1; // 列
$row = 0; // 行

// A1のセルオブジェクトを取得
$cell = $sheet->getCellByColumnAndRow($col, $row)->getValue();

旧処理では列はA=0,B=1…と0始まりで指定されますが、新処理ではA=1,B=2…と1始まりに変更になっています。
普段プログラミングからもずれており、ややこしさを感じますね。

結論

・Excelを使う処理はシンプルであるべき!
特にテンプレートに可変部分を持たせないようにした方がいいですマジで

参考資料

Upgrade Guide | Laravel Excel
PHPExcel と PhpSpreadsheet の比較

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?