我将PHPWord用作My Codeigniter项目中的库。在我的项目中,我想生成一个使用已在工作的模板的.docx文件。该模板中有一个Sticker,它将通过查询数据库中的数据来填充它。由于我想在一个文档中生成多个贴纸,因此我必须复制已经使用的第一个模板并添加一个分页符。但这是行不通的。我无法打开文件。它说:“内容存在问题”。
这是我的代码:
public function Export(){
$this->load->library('PHPWord');
$this->load->model('person_model');
$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$persons= $this->person_model->DataSticker();
$document = $PHPWord->loadTemplate('application/controllers/Sticker.docx');
$counter=1;
foreach($persons as $row){
$this->Doc($document,$counter,$row);
$counter+=1;
if($counter>6){
$counter=1;
$section->addObject($document);
$section->addPageBreak();
$document = $PHPWord->loadTemplate('application/controllers/Sticker.docx');
$this->Doc($document,$counter,$row);
}
}
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$filename = 'nameOfFile.docx';
$objWriter->save( $filename);;
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
readfile($filename);
unlink($filename);
}
public function Doc($document,$counter,$row){
$document->setValue('Fname'.$counter, $row->fname);
$document->setValue('Mname'.$counter, $row->mname);
$document->setValue('Lname'.$counter, $row->lname);
$document->setValue('DOB'.$counter, $row->dob);
$document->setValue('POB'.$counter,$row->pob);
$document->setValue('Age'.$counter, $row->age);
$document->setValue('School'.$counter, $row->school);
}
非常感谢您的帮助。
此答案与0.12.0版本有关(可能也适用于0.13.0)...您可能使用的是旧版本,因为您使用了不赞成使用的loadTemplate函数。
为了回答您的最新问题,我认为您不能将模板与addObject一起使用(好的,不是100%肯定,但是一定要引用)。但是一种可行的方法是使用单个模板文件,在该文件中,您定义了贴纸的一个页面模板(包括分页符),并用模板块标签包裹起来,即:
${CLONEBLOCK}
Here is your sticker page definition (6 stickers + pagebreak)...
${/CLONEBLOCK}
然后在您的代码中,您将根据需要多次克隆此块:
// the class path is probably something different with your codeigniter
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('application/controllers/Sticker.docx');
$templateProcessor->cloneBlock('CLONEBLOCK', count($persons)/6);
您将非常相似地分配模板值:
// note! add the limit 1 as the third parameter (otherwise it will
// write the this value on all of the pages)
$templateProcessor->setValue('Mname'.$counter, $row->mname, 1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句