「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;
}
}
結果
他にも表や画像を貼ったりできます。(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ファイルを変数を動的に埋め込むことができます。
-
テンプレートとなるWordファイルを準備
変数を埋め込みたい場所に ${変数名} と入力しておきます。
今回はこれを /src に /word と言うディレクトリを作り template.docx として入れておきました。 -
値を代入
<?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が出力されてしまいます。
結果
実は
これがQiita 初投稿です。プログラミング歴もうすぐで一年になります。
間違っているところや改善すべき点がある場合は指摘していただけると幸いです。