TP5利用phpforword生成word表格文檔

1.首先用composer安裝下載 phpoffice/phpforword

composer require phpoffice/phpword

image.png

2.在controller裏引用

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

3.生成簡單表格代碼如下

$PHPWord = new PhpWord();
$section = $PHPWord->createSection();
$PHPWord->addTitleStyle(1, array('bold' => true, 'size' => 18, 'name' => 'Arial', 'Color' => '333'), array('align' => 'center'));
$section->addTitle("編程愛好者之家", 1);

//定義樣式數組
$styleTable = array(
    'borderSize'=>6,
    'borderColor'=>'000000',
    'cellMargin'=>150
);
$styleFirstRow = array(
    'borderBottomSize'=>18,
    'borderBottomColor'=>'000000',
    'bgColor'=>'66bbff'
);

$cellStyle = array('gridSpan' => 2);


//添加表格樣式
$PHPWord->addTableStyle('myOwnTableStyle',$styleTable,$styleFirstRow);

//添加表格
$table = $section->addTable('myOwnTableStyle');

$table->addRow();
$table->addCell(3000)->addText('測試1');
$table->addCell(3000)->addText('測試2');
$table->addCell(3000)->addText('測試3');

$table->addRow();
$table->addCell(3000)->addText('測試4');
$table->addCell(6000,$cellStyle)->addText('測試5'); //合併列單元格


$table->addRow();
$table->addCell(3000,array('vMerge' => 'restart'))->addText('合併');
$table->addCell(3000)->addText('測試6');
$table->addCell(3000)->addText('測試7');
$table->addRow();
$table->addCell(3000,array('vMerge' => 'continue'));
$table->addCell(3000)->addText('測試8');
$table->addCell(3000)->addText('測試9');

$table->addRow();
$table->addCell(3000)->addText('測試10');
$table->addCell(3000)->addText('測試11');
$table->addCell(3000)->addText('測試12');


$file = '測試.docx';

//文檔存在服務器上用此代碼
$objWriter = IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('存儲地址/編程愛好者.docx');

//直接下載不存儲在服務器上用此代碼
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = IOFactory::createWriter($PHPWord, 'Word2007');
$xmlWriter->save("php://output");

生成文檔如下圖所示

image.png

原文地址:https://www.codelovers.cn/article/20191218110020.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章