Created
January 12, 2017 09:56
-
-
Save hidesakai/adeb9207340206ed8b94e7b540d37dc9 to your computer and use it in GitHub Desktop.
PHPExcelですべてのシートデータをJSONに変換する ref: http://qiita.com/hidesakai/items/32b5e7ca1659782b99bc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment