PHPWord保存目录

时间:2015-08-28 00:48:58

标签: php phpword

我不知道为什么但是我很难让PHPWord正常运行。解决错误我相信我的下面的代码正在运行但我找不到任何输出。所以要么1)它没有输出任何东西或2)我找不到保存的文件(虽然我相信我已经看过每个目录)。有没有人有任何想法?感谢

require_once '/home/public_html/biz/PHPWord-master/src/PhpWord/Autoloader.php';
    \PhpOffice\PhpWord\Autoloader::register();
    require_once '/home/public_html/biz/PHPWord-master/src/PhpWord/PhpWord.php';
    $PHPWord = new \PhpOffice\PhpWord\PhpWord();
    $document = $PHPWord->loadTemplate('/home/public_html/biz/WordTemp.docx');

    $document->setValue('HERE', 'test');

    // Saving the document as OOXML file...
    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
    $objWriter->save('helloWorld.docx');

1 个答案:

答案 0 :(得分:0)

如果我正确地理解你正在尝试处理模板。 也许我错了,但你只能通过TemplateProcessor来做到这一点。

我使用这样的东西。我希望它有所帮助。

<?php
function processTemplate($templateFile,$outputFile,$data){
    //PHPWORD INIT
        require_once __DIR__ . '/../src/PhpWord/Autoloader.php';//Your actual path here obviously, here it is set for the sample dir

        \PhpOffice\PhpWord\Autoloader::register();

        // Template processor instance creation
        $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($templateFile);
    //CORE
        foreach($data as $key => $value){
            if(is_array($value)) {
                $rowNum = sizeof($value);
                $actRow = 0;
                $templateProcessor->cloneRow($key, $rowNum);
                foreach($value as $row) {
                    $actRow++;
                    foreach($row as $col => $cellValue){
                        $templateProcessor->setValue($col."#".$actRow, $cellValue);
                    }
                }
            }else{
                $templateProcessor->setValue($key, $value);
            }
        }

    //SAVING FILE
        $templateProcessor->saveAs($outputFile);
    return true;
}
//example
$data = array(

        "setval1" => "Orange",//for setvalue

        "setval2" => "Apple", //for setvalue

        "clonerow1" => array(

            array("clonerow1" => "First entry","animal" => "Elephant","owner" => "Jack"),

            array("clonerow1" => "Second entry","animal" => "Cat", "owner" => "Alice")

        ) //for clonerow

    );
?>