PHP 創建 word 文件

官網地址: PHPOffice/PHPWord

// 初始化
$phpWord = new \PhpOffice\PhpWord\PhpWord();
// 增加一個空白頁面
$section = $phpWord->addSection();

 文字的樣式,包括字體、顏色、字號、粗體

// 字體樣式
$fontStyle = [
  'name' => 'Microsoft Yahei UI',
  'size' => 20,
  'color' => '#ff6600',
  'bold' => true
];
$textrun = $section->addTextRun();  // 運行文本

// 如果創建文件後打開提示非法字符 轉義字符
$text='你好,這是生成的Word文檔。 ';
$word='<';// 這裏舉例,也包括其他特殊字符
$new_text=htmlspecialchars($word);

$section->addTextBreak(1);// 添加換行符
$textrun->addText($text.$new_text, $fontStyle); // 添加文本

可以爲Word文檔中的文字添加用於點擊跳轉的鏈接

$section->addLink('https://www.helloweba.net', '歡迎訪問Helloweba', array('color' => '0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));

可以在word中添加圖片,如圖片地址logo.png,尺寸爲64x64。圖片源也可以是遠程圖片

$section->addImage('logo.png', array('width'=>64, 'height'=>64));

爲Word文檔添加頁眉

$header = $section->addHeader();
$header->addText('Subsequent pages in Section 1 will Have this!');
//爲word文檔添加頁腳,頁腳內容是頁碼,格式居中。
$footer = $section->addFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', null, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER));

增加一個基礎表格,可以設置表格的樣式

$header = array('size' => 16, 'bold' => true);
$rows = 10;
$cols = 5;
$section->addText('Basic table', $header);
$table = $section->addTable();
for ($r = 1; $r <= 8; $r++) {
  $table->addRow();
  for ($c = 1; $c <= 5; $c++) {
    $table->addCell(1750)->addText("Row {$r}, Cell {$c}");
  }
}

生成word文檔

// 放服務器上
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('hellwoeba.docx');

// 直接下載Word文檔,不在服務器上保存的話,可以使用:
$file = 'test.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 = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");

 

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