LoginSignup
2
2

More than 5 years have passed since last update.

PHPExcelですべてのシートデータをJSONに変換する

Posted at

自分用メモ

Excelで複数シートにまたがる、数千レコードのデータをJSONに変換する必要があったので、PHPExcelを使って変換してみた。

環境

  • MacOS(Elcapitan)
  • PHP 7.0.10
  • PHPExcel v1.8.1

PHPExcel インストール

composerでインストールするのが一番早そうです。

composer require phpoffice/phpexcel

変換してみる

convert-excel-to-json.php
<?php
// composer require phpoffice/phpexcel
require "vendor/autoload.php";

// Memory CacheだとFatal Errorが発生するため、"/tmp"にFile Cacheとして保存する
$cacheSettings = array("dir" => "/tmp");
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

// Excelファイル読み込み
$reader = PHPExcel_IOFactory::createReader("Excel2007");
$book   = $reader->load("foo.xlsx");

// getSheetNames()ですべてのシート名を配列として取得
foreach ($book->getSheetNames() as $sheetName) {
    // シート名からレコードを取得
    $sheet = $book->getSheetByName($sheetName);
    $items = $sheet->toArray(null, false, true, true);

    foreach ($items as $item) {
        // 余分な空配列を除去
        if ($item = array_filter($item)) {
            $records[$sheetName][] = $item;
        }
    }
}

// JSONファイルとして保存
$fp = fopen("bar.json", "a") or dir("Can't open file");
fwrite($fp, json_encode($records, JSON_PRETTY_PRINT));
fclose($fp);

PHPExcelを読み込んでデータ取得するだけなので簡単だと考えていたけど、数千レコードあるためかメモリー足りずにFatal errorが出てにっちもさっちもいかない状態で困った。ファイル分割すれば良かったんだけど、シートだけでも数十あったので回避策探したほうが早そうだったので、以下の記事参考にキャッシュ方法変更してみる。

PHPExcelで大きいエクセルファイルを読み込んだ際にFatal error: Allowed memory size of XXXXX exhausted

あと、↓みたいなシートの取り方もあるみたいなので、お好きな方で

// Excelファイル読み込み
$reader = PHPExcel_IOFactory::createReader("Excel2007");
$book   = $reader->load("foo.xlsx");

// シート数
$count = $book->getSheetCount();
for ($i = 0; $i < $count; $i++) {
    // 指定位置のシートを取得
    $book->setActiveSheetIndex($i);
    $sheet = $book->getActiveSheet();
}
2
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
2
2