【php】PHPExcelでxlsxファイルを読む・書く
2019/05/31
php
<?php require_once 'Classes/PHPExcel/IOFactory.php'; $book = PHPExcel_IOFactory::load("sample.xlsx"); $book->setActiveSheetIndex(0); // 一番最初のシートを選択(2枚目なら(1)) $sheet = $book->getActiveSheet(); // 現在選択中のシート // シート名を設定できる $sheet->setTitle('シート名変更テスト'); // データのある範囲をまとめて配列に読み込む $a = $sheet->toArray(null, true, true, true); var_dump($a); /* array(34) { [1]=> array(41) { ["A"]=> string(33) "なんたらかんたら123" ["B"]=> NULL ["C"]=> */ // 読む $x = $sheet->getCellByColumnAndRow(0, 9)->getValue(); $y = $sheet->getCell('C9')->getValue(); /* // 行イテレータ取得 $sheetData = array(); foreach ($sheet->getRowIterator() as $row) { $tmp = array(); // 列イテレータ取得 foreach ($row->getCellIterator() as $cell) { // セルの値取得 $tmp[] = $cell->getValue(); } $sheetData[] = $tmp; } */ // 書く $sheet->setCellValue('A1','書き込み内容'); //セル位置指定 //列はA=0,B=1... 行はそのまま $sheet->setCellValueByColumnAndRow(0, 3, '書き込み内容'); // 保存 $writer = PHPExcel_IOFactory::createWriter($book, 'Excel2007'); $writer->save('sample2.xlsx'); // ダウンロードさせる場合 /* header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename=sample2.xlsx'); $writer = PHPExcel_IOFactory::createWriter($book, "Excel2007"); $writer->save('php://output'); */ /* header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename=sample2.xls'); $writer = PHPExcel_IOFactory::createWriter($book, "Excel5"); $writer->save('php://output'); */
日付形式のセルのデータを読む
$x = PHPExcel_Style_NumberFormat::toFormattedString($value, PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
コメント