0
1

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 1 year has passed since last update.

【Excel】PhpSpreadsheetの使用

Last updated at Posted at 2023-03-10

PhpSpreadsheetの使用

PhpSpreadsheetのインストール

  • comporserで使用したいディレクトリにPhpSpreadsheetをインストール
composer require phpoffice/phpspreadsheet

空のExcelファイルを作成

  • PhpSpreadsheetをインストールしたディレクトリにcreateExcel.phpを作成。
createExcel.php
<?php
require_once "vendor/autoload.php";
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// ここで $sheet を通してセルなどを操作します。

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('対象ディレクトリ/createExcel.xlsx');
  • 実行ディレクトリからphp 対象ディレクトリ/createExcel.phpを実行すると対象ディレクトリ内に空のExcelファイルが作成される。
  • この時対象ディレクトリはあらかじめ作成しておく必要がある。

空のExcelファイルに日付を入力

  • createExcel.xlsx と同階層にeditExcel.php を作成します。
editExcel.php
<?php
require_once "vendor/autoload.php";

use PhpOffice\PhpSpreadsheet\Reader\Xlsx as Reader;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as Writer;

$reader = new Reader;
$file_name = 'createExcel.xlsx';
$spreadsheet = $reader->load($file_name);

$sheet = $spreadsheet->getActiveSheet();
date_default_timezone_set('Asia/Tokyo');
// 文字の入力
$sheet->setCellValue('A1', 'テスト文字列');
// 日付の入力
$sheet->getCell( 'B2' )->setValue( date("Y/m/d H:i:s") );
// 空白の入力
$sheet->setCellValue('D1', null);

$writer = new Writer($spreadsheet);
$outputPath = 'createExcel.xlsx';
$writer->save( $outputPath );
  • これをターミナルで実行php editExcel.phpすると先ほど作った空のExcelに日付が追加されている。

sheetの値の取得

  • 新しくread.php ファイルを作成し、シートを読み込んで値を取得する。
read.php
<?php
require_once "vendor/autoload.php";

use PhpOffice\PhpSpreadsheet\Reader\Xlsx as Reader;

$reader = new Reader;
$file_name = 'read.xlsx';
$spreadsheet = $reader->load($file_name);

// シートの読み込み
$sheet = $spreadsheet->getActiveSheet();

// 値の取得
$URL = $sheet->getCell('C2')->getValue();
$value = $sheet->getCell('F2')->getValue();
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?