Office関連

PHPWordを使ってPHPからWordファイルを出力してみる。

最近オトカドールルミティアジュエルやらの記事ばかり書いていますが、今回はOffice系MVPらしくWordネタを書いていこうと思います。

今回紹介するのは「PHPWord」。
文字通り、PHPからWordファイルを出力するためのライブラリです。

Composerのインストール

上記GitHubのページにも書いてありますが、PHPWordはComposerを使ってインストールします。
(Composerはプロジェクト単位でパッケージ管理できるので、お手軽で便利です。)

インストールは簡単で、Windowsの場合ダウンロードページから「Composer-Setup.exe」ファイルをダウンロードして実行するだけです。
詳しい手順はこちらの記事に書かれているので、左記ページをご参照ください。

PHPWord_01

PHPWord_02

PHPWord_03

PHPWord_04

PHPWord_05

PHPWord_06

PHPWordのインストール

Composerのインストールが終わったら、次はPHPWordのインストールです。
composer.jsonファイルを下記のように記述して「composer install」コマンドを実行すると・・・

{
    "require": {
       "phpoffice/phpword": "v0.13.*"
    }
}
Problem 1
    - The requested package phpoffice/phpword v0.13.* exists as phpoffice/phpword[0.10.0, 0.10.1, 0.11.0, 0.11.1, 0.12.0, 0.7.0, 0.8.0, 0.8.1, 0.9.0, 0.9.1, dev-develop, dev-master, v0.12.1] but these are rejected by your constraint.

PHPWord_07

GitHubのコードをコピペしたのに怒られました。
仕方がないのでバージョン指定してインストールします。

{
    "require": {
       "phpoffice/phpword": "v0.12.1"
    }
}

今度は上手くいきました。
vendorフォルダもちゃんと作成されています。

PHPWord_08

PHPWord_09

PHPWordの呼び出し

PHPWordのインストールが終わったので、いよいよPHPから呼び出してみます。

<?php
    require_once './vendor/autoload.php';
    
    $phpWord = new \PhpOffice\PhpWord\PhpWord();
    $section = $phpWord->addSection();
    
    $fontStyle = new \PhpOffice\PhpWord\Style\Font();
    $fontStyle->setBold(true);
    $fontStyle->setName('MS Pゴシック');
    $fontStyle->setSize(24);
    $myTextElement = $section->addText('こんにちは、世界。');
    $myTextElement->setFontStyle($fontStyle);
    
    //ダウンロード用
    header("Content-Description: File Transfer");
    header('Content-Disposition: attachment; filename="sample.docx"');
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Expires: 0');
    $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    ob_end_clean(); //バッファ消去
    $xmlWriter->save("php://output");

・・・が、まさかのFatal error。

Fatal error: Cannot use PhpOffice\PhpWord\Shared\String as String because 'String' is a special class name in C:\xampp\htdocs\PHPWord\vendor\phpoffice\phpword\src\PhpWord\Style\AbstractStyle.php on line 20

PHP 7だと型名と同じクラス名が作れないようです。なるほど。

ならば仕方がないので、PHP 5.6を使ってみると・・・

PHPWord_10

PHPWord_11

今度は無事にコードが実行され、Wordファイルの作成を確認できました。
日本語も問題なく表示され、フォントも指定したものになっています。

PHPWord_12

ファイルの新規作成だけでなく、下図のように既存ファイルを読み込んで、指定部分を置き換えることもできます。

<?php
    require_once './vendor/autoload.php';
    
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
    $templateProcessor->setValue('name', '佐藤');
    $templateProcessor->setValue('weather', 'くもり');
    
    //ダウンロード用
    header("Content-Description: File Transfer");
    header('Content-Disposition: attachment; filename="sample2.docx"');
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Expires: 0');
    ob_end_clean(); //バッファ消去
    $templateProcessor->saveAs("php://output");

PHPWord_13

PHPWord_14

短いコードでWordファイルの編集・保存ができる便利なライブラリです。
ドキュメントサンプルコードも充実しているので、興味がある方は是非お試しください。

【オトカドール】ツブレトマトの動画を撮ってきました。前のページ

【オトカドール】イントロダクションがはじまったよ。次のページ

関連記事

  1. Office関連

    ExcelとPowerPointに自動保存機能が追加されました。

    Excel 2016を使っていて、ふと気が付いたのが画面左上にある「自…

  2. Office関連

    代替テキストを削除するPowerPointマクロ

    PowerPointの図やSmartArt、グループやグラフといった視…

  3. Office アドイン

    [Office用アプリ]Apps for Office サミット!で登壇しました。

    21日(土)に開催されたOffice 用アプリの勉強会「Apps fo…

  4. Office関連

    選択中の表の行数を取得するWordマクロ

    「Word VBA 表 行数」といったキーワード検索でのアクセスがあり…

  5. Office関連

    [VBA]ユーザーフォーム上のコンボボックスでオートコンプリート機能を実装する方法

    MSDNフォーラムに「ユーザーフォーム上のコンボボックスで、任意の文字…

コメント

  • コメント (0)

  • トラックバックは利用できません。

  1. この記事へのコメントはありません。

Time limit is exhausted. Please reload CAPTCHA.

※本ページはプロモーションが含まれています。

Translate

最近の記事

アーカイブ

PAGE TOP