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

Ras*_*san 3 php export-to-word laravel phpword phpdocx

我正在尝试将用户详细信息导出到.docx文件。该文件已成功导出,但是正在提供对象。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'));
}
Run Code Online (Sandbox Code Playgroud)

下载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"}
Run Code Online (Sandbox Code Playgroud)

我想获取格式正确的结果,例如标头“名称”,“电子邮件”等。

eMM*_*eMM 5

步骤1:.docx使用文字处理程序(OpenOffice,LibreOffice Writer,MS Word等) 创建文件,该程序将用作“用户文档”的模板(通过这种方式,您可以设置大小,边距,方向和其他属性,以及使用您使用的文字处理程序中提供的工具创造性地设置文档格式)。

对于文档中的动态值,可以将变量用作占位符。文档变量的语法为${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); 
Run Code Online (Sandbox Code Playgroud)

步骤4: 生成一个安全的文件名(user_1.docx即)

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

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

步骤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'));
}
Run Code Online (Sandbox Code Playgroud)