PHPでExcelデータを表示するメモ
PHPでExcelファイルの内容を一覧表示するためのメモ。
Excelファイルを扱うのは厄介ですが、PHPExcel を使えば比較的容易に扱うことができます。Excelファイルを作成したりファイルの内容を一括で取得して配列に突っ込んだり…のサンプルは多いものの、fget_csv()
みたいに一件ずつ処理していくサンプルが少なかったので自分用に方法をメモ。
主に、以下のページを参考にしています。
以下、xlsx
か xls
ファイルの内容をテキストデータとして取得するメモ。最終的には配列に突っ込んでいるけど、個別に処理するのも難しくないです。
<?php
echo "<!DOCTYPE html>\n";
echo "<html lang=\"ja\">\n";
echo "<head>\n";
echo "<meta charset=\"utf-8\" />\n";
echo "<title>Excel</title>\n";
echo "</head>\n";
echo "<body>\n";
echo "<h1>Excel</h1>\n";
echo "<pre>\n";
//読み込むExcelファイル
$file = './sample.xlsx';
//ライブラリを読み込む
require_once '../Classes/PHPExcel/IOFactory.php';
//ファイルを読み込む
if (preg_match('/\.xlsx$/', $file)) {
$type = 'Excel2007';
} elseif (preg_match('/\.xls$/', $file)) {
$type = 'Excel5';
} else {
exit('error');
}
$reader = PHPExcel_IOFactory::createReader($type);
$excel = $reader->load($file);
//シートオブジェクトの取得
$sheets = $excel->getAllSheets();
//$sheets[0] = $excel->getSheet(0);
$data = array();
//シートごとに処理
foreach ($sheets as $s => $sheet) {
//シート名を取得
$data[$s]['title'] = $sheet->getTitle();
//列数と行数を取得
$row_max = $sheet->getHighestRow();
$col_max = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1;
//セルごとにテキストデータを取得
$content = array();
$flag = false;
for ($r = 1; $r <= $row_max; $r++) {
for ($c = 0; $c <= $col_max; $c++) {
$text = get_text($sheet->getCellByColumnAndRow($c, $r));
if (!is_null($text) and $flag == false) {
$flag = true;
}
$content[$r][$c] = $text;
}
}
if ($flag == false) {
$content = array();
}
//データをセット
$data[$s]['content'] = $content;
}
//結果を出力
print_r($data);
echo "</pre>\n";
echo "</body>\n";
echo "</html>\n";
exit;
/* 指定したセルの文字列を取得 */
function get_text($cell = null)
{
if (is_null($cell)) {
return null;
}
$value = $cell->getValue();
if (is_object($value)) {
//オブジェクトが返ってきたら、リッチテキスト要素を取得
$rich_texts = $value->getRichTextElements();
//配列で返ってくるので、そこからさらに文字列を抽出
$texts = array();
foreach ($rich_texts as $rich_text) {
$texts[] = $rich_text->getText();
}
//連結する
$text = implode('', $texts);
} else {
if (empty($value)) {
$text = null;
} else {
$text = $value;
}
}
return $text;
}
?>