在 laravel 中使用 PHPWord 导出到 docx 时传递动态值

pass dynamic values when export to docx using PHPWord in laravel

我正在尝试将用户详细信息导出到 .docx 文件。文件已成功导出,但显示 object。 Phpword 格式无效。如何编写代码以正确导出动态值,请有人帮助我吗?

AdminController.php-

public function exportUserToDoc(Request $request, $id)
{
    $wordTest = new \PhpOffice\PhpWord\PhpWord();
    $newSection = $wordTest->addSection();

    $desc1 = User::find($id);

    $newSection->addText($desc1, array('name' => $desc1->name, 'email' => $desc1->email, 'phone' => $desc1->phone, 'address' => $desc1->address));
    $objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordTest, 'Word2007');
    try{
        $objectWriter->save(storage_path('TestWordFile.docx'));
    }catch (Exception $e){

    }
    return response()->download(storage_path('TestWordFile.docx'));
}

下载 doc 文件后结果如下 -

{"id":1,"name":"Emdadul Huq Shikder","email":"emdadulshikder@gmail.com","phone":"+8801674338411","address":"59\/6\/1 West Razabazar, Dhaka","status":0,"created_at":"2018-03-13 05:18:32","updated_at":"2018-03-13 05:35:51"}

我想获得格式正确的结果,例如 header 'Name'、'Email' 等

第 1 步: 使用文字处理程序(OpenOffice、LibreOffice Writer、MS Word 等)创建一个 .docx 文件,该文件将用作 'User Document' 的模板(这样您可以设置大小、边距、方向和其他属性,并使用您使用的文字处理程序中提供的工具创造性地设置文档格式。

对于文档中的动态值,您可以使用变量作为占位符。文档变量的语法是 ${variable}。确保您的变量名称是唯一的。

这是带有文档变量的示例文档模板的屏幕截图。

第 2 步: 将您的文档模板上传到服务器的存储路径。

第 3 步: 创建一个新的 TemplateProcessor 并为您放置在文档模板中的变量赋值。

$desc1 = User::find($id);   

$my_template = new \PhpOffice\PhpWord\TemplateProcessor(storage_path('user_template.docx'));

$my_template->setValue('name', $desc1->name);
$my_template->setValue('email', $desc1->email);
$my_template->setValue('phone', $desc1->phone);
$my_template->setValue('address', $desc1->address); 

第 4 步: 生成安全文件名(user_1.docx 即)

第 5 步: 使用您在上一步中生成的安全文件名从您的模板创建一个 .docx 文件。

try{
    $my_template->saveAs(storage_path('user_1.docx'));
}catch (Exception $e){
    //handle exception
}

第 6 步: 下载已保存文件的完整代码片段。

public function exportUserToDoc(Request $request, $id)
{
    $desc1 = User::find($id);

    $my_template = new \PhpOffice\PhpWord\TemplateProcessor(storage_path('user_template.docx'));

    $my_template->setValue('name', $desc1->name);
    $my_template->setValue('email', $desc1->email);
    $my_template->setValue('phone', $desc1->phone);
    $my_template->setValue('address', $desc1->address);      

    try{
        $my_template->saveAs(storage_path('user_1.docx'));
    }catch (Exception $e){
        //handle exception
    }

    return response()->download(storage_path('user_1.docx'));
}
public function wordExport($id){
    $doc = Doc::find($id);

    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('word-template/document.docx');

    $title = $doc->title;
    $reg = $doc->reg;

    $templateProcessor->setValue('title', $title);
    $templateProcessor->setValue('reg', $reg);

    $fileName = $title;
    $templateProcessor->saveAs($fileName . '.docx');
    return response()->download($fileName . '.docx')->deleteFileAfterSend(true);
}