PHPWord導出word文檔


最近接了個把數據導出到word文檔的需求,之前一直都是使用PHPExcel庫導出excel的,還是頭次接到導出到word文檔的需求,我想既然有PHPExcel,那么肯定也會有PHPWord庫吧,在網上一搜,還真有!而且都是phpoffice家的。看了下文檔,最終決定使用模板的方式來導出數據,感覺也是最簡單的一種方式了。

過程如下:

使用composer下載PHPWord到項目中

composer require phpoffice/phpword

可以看到,phpword的下載量還是挺高的

下載完后就可以開始制作我們的需求模板了,如下圖所示,模板中使用${變量名}作為占位符,到時候用代碼替換即可,${company_name}、${pic}等都是占位符

制作好模板就可以開始寫代碼了。

//導出word大致可以分為三步
//1.創建模板對象
$document = new TemplateProcessor('./template.docx');

//2.插入數據
//插入文字
$document->setValue('company_name', 'XXX有限公司');


//插入圖片
$document->setImageValue('pic1', './img/gyy.jpeg');
$document->setImageValue('pic2', './img/zyt.jpeg');

//插入文字
$document->setValue('organizationo', '123456');

//3.保存文件
$document->saveAs('./target.docx');

導出效果如下:

可以看到默認導出都word的圖片比較小,phpword支持自定義圖片的大小,這里需要修改setImageValue方法的第二個參數,如果想自定義寬高就需要傳入一個數組,格式如下

array("path" => xx, "width" => yy, "height" => zz)

path代表要插入圖片的路徑,width和height分別代表寬高

修改后的代碼如下:

//1.創建模板對象
$document = new TemplateProcessor('./template.docx');

//2.插入數據
//插入文字
$document->setValue('company_name', 'XXX有限公司');


//插入圖片,寬200像素,高300像素
$picParam = ['path' => './img/gyy.jpeg', 'width' => 200, 'height' => 300]; 
$document->setImageValue('pic1', $picParam);

$picParam2 = ['path' => './img/zyt.jpeg', 'width' => 200, 'height' => 300];
$document->setImageValue('pic2', $picParam2);

//插入文字
$document->setValue('organizationo', '123456');

//3.保存文件
$document->saveAs('./target.docx');

最終導出效果如下:

圖片變成了我們期望的大小了。

如果想把生成的文件下載到瀏覽器,可以在生成文件后加上如下代碼即可

//4.從瀏覽器下載
ob_clean();
ob_start();
$fp = fopen('./target.docx',"r");
$file_size = filesize('./target.docx');
Header("Content-type:application/octet-stream");
Header("Accept-Ranges:bytes");
Header("Accept-Length:".$file_size);
Header("Content-Disposition:attchment; filename=".'測試文件.docx');
$buffer = 1024;
$file_count = 0;
while (!feof($fp) && $file_count < $file_size){
    $file_con = fread($fp,$buffer);
    $file_count += $buffer;
    echo $file_con;
}
fclose($fp);
ob_end_flush();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM