0
0

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

CakePHPでPHPWordを使う方法

Posted at

「CakePHP PHPWord」と調べてもひとつも出てこなかったので、PHPSpreadsheetに関する記事を参考にしながらなんとか実装しました。そのなけなしの成果を書いておきます。
CakePHP4を使っています。

インストール

composerを使ってインストールします。

composer require phpoffice/phpword

サーバー上に保存

/webroot に sample.docx が作成されるようにしています。

<?php

namespace App\Controller;

use PhpOffice\PhpWord\PhpWord;//<-追加
use PhpOffice\PhpWord\IOFactory;//<-追加


class SapmleController extends AppController
{
    public function word()
    {
        $word = new PhpWord();
        $section = $word->addSection();
        $section->addText("テスト");
        $section->addText(
            'ほげほげ',
            ['name' => 'MS ゴシック', 'size' => 15, 'color' => '00ff00', 'bold' => true, 'underline' => 'dash']
        );
        $writer = IOFactory::createWriter($word, 'Word2007');
        $writer->save(WWW_ROOT . 'sample.docx');
        exit;
    }
}

結果

スクリーンショット 2020-10-26 10.22.56.png

他にも表や画像を貼ったりできます。(https://qiita.com/satthi/items/761f7d956e2e9ca76f53)

ダウンロード

サーバに保存するのではなく、ブラウザでダウンロードさせたい場合はこのようにします。

<?php

namespace App\Controller;

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;


class SapmleController extends AppController
{
    public function download()
    {
        $word = new PhpWord();
        $section = $word->addSection();
        $section->addText("テスト");
        $section->addText(
            'ほげほげ',
            ['name' => 'MS ゴシック', 'size' => 15, 'color' => '00ff00', 'bold' => true, 'underline' => 'dash']
        );
        $writer = IOFactory::createWriter($word, 'Word2007');

        //ここから下を変更
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment;filename="sample.docx');
        header('Cache-Control: max-age=0');
        //ダウンロード
        $writer->save('php://output');
        exit;
    }
}

テンプレート機能

TemplateProcessorを使えば以下のようにテンプレートのwordファイルを変数を動的に埋め込むことができます。

  1. テンプレートとなるWordファイルを準備
    変数を埋め込みたい場所に ${変数名} と入力しておきます。
    スクリーンショット 2020-10-26 10.54.21.png
    今回はこれを /src に /word と言うディレクトリを作り template.docx として入れておきました。

  2. 値を代入

<?php

namespace App\Controller;

use PhpOffice\PhpWord\TemplateProcessor;//<-変更


class SapmleController extends AppController
{
    public function template()
    {
        $template_path  = realpath(APP) . DS .  "word" . DS . "template.docx";

        $templateProcessor = new TemplateProcessor($template_path);
        //値を代入
        $templateProcessor->setValue('hoge', "ほげほげ");
        $templateProcessor->setValue('huga', "フガふが");

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment;filename="sample.docx"');
        header('Cache-Control: max-age=0');

        //ダウンロード
        $templateProcessor->saveAs('php://output');
        exit;
    }
}

->save ではなく ->saveAs とすることに気をつけてください。そうしないと何も書かれていない白紙のwordが出力されてしまいます。

結果

スクリーンショット 2020-10-26 11.13.44.png


実は

これがQiita 初投稿です。プログラミング歴もうすぐで一年になります。
間違っているところや改善すべき点がある場合は指摘していただけると幸いです。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?