16
17

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 5 years have passed since last update.

PHPで手軽にExcelの表を読みたい

Last updated at Posted at 2015-06-01

データを Excel 形式で入手したときに、とにかくパッとデータを扱いやすい形式に変換したい、という時に便利です。

Excel は御存知の通り色々できるので、読んだデータが何かと加工されていたらプレーンテキストに変換するなどの処理が必要かもしれません。 (けど、私は幸いにも特にそういった必要性がなかったのでそのことには触れません)

PHPExcel を使う

そういうライブラリがあるので使います。

composer require phpoffice/phpexcel

データを配列として取得する

excel_dumper.php
<?php

require_once __DIR__ . '/vendor/autoload.php';

function excel_dump($path)
{
    $excel = PHPExcel_IOFactory::createReader('Excel5');
    $book = $excel->load($path);
    $sheet = $book->getActiveSheet();
    return $sheet->toArray(null, true, true, true);
}

$data = excel_dump('/path/to/excel/book.xls');
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

結果

[
  {
    "A": "107-0062",
    "B": "東京都",
    "C": "港区",
    "D": "南青山",
    "E": "2丁目2番15号",
    "F": "ウイン青山1403",
    "G": "Increments株式会社"
  },
  {
    "A": "省略……",
    "B": "省略……",
    "C": "省略……",
    "D": "省略……",
    "E": "省略……",
    "F": "省略……",
    "G": "省略……"
  }
]

補足

*.xls ではなく *.xlsx の場合は createReader に渡す引数を Excel2007 にして下さい。

16
17
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
16
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?