【问题标题】:generate template from database从数据库生成模板
【发布时间】:2021-09-26 17:34:30
【问题描述】:

我正在尝试使用 PhpWord 库来使用 Laravel 生成 Word 文件。

我搜索了这个库的文档以及它是如何工作的,我发现我应该已经有了一个可以使用的模板。

但就我而言,我应该从数据库中创建此模板,然后以 word 格式生成此文件。

我正在尝试以下代码:

$preambule = DB::table('modele_contrat')->select('preambule')->where('id_modele_contrat', $value['id_modele_contrat'])->value('preambule');                         
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$text = $section->addText($preambule);
 $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
 $objWriter->save('testt.docx');
 return response()->download(public_path('testt.docx'));

但是在这种情况下,文件没有打开并出现错误,在文件内容中检测到问题。

但是当我改变这一行的代码时: $text = $section->addText($preambule);

到:

 $text = $section->addText("hello");

文件正常打开。

当我做 dd($preambule) 来查看这个变量的值时,我得到了存储在数据库列中的值,一个 varchar 元素。

【问题讨论】:

  • 我认为问题在于您的查询使用此:$preambule = DB::table('modele_contrat')->where('id_modele_contrat', $value['id_modele_contrat'])->get();$preambule->preambule

标签: laravel phpword


【解决方案1】:
$preambule = DB::table('modele_contrat')->where('id_modele_contrat', $value['id_modele_contrat'])->value('preambule');

$phpWord = new \PhpOffice\PhpWord\PhpWord();

$sectionStyle = array(
    //'orientation'       =>      'landscape',
    'marginTop'         =>      600,
    'marginRight'       =>      600,
    'marginBottom'      =>      600,
    'marginLeft'        =>      600,
    //'text-align'        =>      'right',
    'footerHeight'      =>      100
);

$section = $phpWord->addSection($sectionStyle);

$section->addText($preambule);

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
try {
    $objWriter->save(storage_path('preambule.docx'));
} catch (Exception $e) {
}
return response()->download(storage_path('preambule.docx'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 2018-12-12
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多