一、安裝
直接使用composer安裝,鏈接地址
composer require phpoffice/phpword
二、簡單使用
require_once 'PhpOffice/PhpWord/PhpWord.php'; // 包含頭文件
use PhpOffice\PhpWord\Autoloader;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\IOFactory;
require_once __DIR__ . '/PhpOffice/PhpWord/Autoloader.php';
Autoloader::register();
Settings::loadConfig();
// Create a new PHPWord Object
$PHPWord = new \PhpOffice\PhpWord\PhpWord();
$PHPWordHelper= new \PhpOffice\PhpWord\Shared\Font();
$PHPWord->setDefaultFontName('仿宋'); // 全局字體
$PHPWord->setDefaultFontSize(16); // 全局字號為3號
// 設置文檔的屬性,這些在對文檔右擊屬性可以看到,也可以省去這些步驟
$properties = $PHPWord->getDocumentProperties();
$properties->setCreator('張三'); // 創建者
$properties->setCompany('某公司'); // 公司
$properties->setTitle('某某文檔'); // 標題
$properties->setDescription('http://wangye.org'); // 描述
$properties->setLastModifiedBy('李四'); // 最后修改
$properties->setCreated( time() ); // 創建時間
$properties->setModified( time() ); // 修改時間
// 添加3號仿宋字體到'FangSong16pt'留着下面使用
$PHPWord->addFontStyle('FangSong16pt', array('name'=>'仿宋', 'size'=>16));
// 添加段落樣式到'Normal'以備下面使用
$PHPWord->addParagraphStyle(
'Normal',array(
'align'=>'both',
'spaceBefore' => 0,
'spaceAfter' => 0,
'spacing'=>$PHPWordHelper->pointSizeToTwips(2.8),
'lineHeight' => 1.19, // 行間距
'indentation' => array( // 首行縮進
'firstLine' => $PHPWordHelper->pointSizeToTwips(32)
)
)
);
// Section樣式:上3.5厘米、下3.8厘米、左3厘米、右3厘米,頁腳3厘米
// 注意這里厘米(centimeter)要轉換為twips單位
$sectionStyle = array(
'orientation' => null,
'marginLeft' => $PHPWordHelper->centimeterSizeToTwips(3),
'marginRight' => $PHPWordHelper->centimeterSizeToTwips(3),
'marginTop' => $PHPWordHelper->centimeterSizeToTwips(3.5),
'marginBottom' => $PHPWordHelper->centimeterSizeToTwips(3.8),
'pageNumberingStart' => 1, // 頁碼從1開始
'footerHeight' => $PHPWordHelper->centimeterSizeToTwips(3),
);
$section = $PHPWord->addSection($sectionStyle); // 添加一節
// 下面這句是輸入文檔內容,注意這里用到了剛才我們添加的
// 字體樣式FangSong16pt和段落樣式Normal
$section->addText('文檔內容', 'FangSong16pt', 'Normal');
$section->addTextBreak(1); // 新起一個空白段落
$objWriter = IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('/path/to/file'); // 保存到/path/to/file路徑下
