shifu204

官方文档  github地址

 

一、安装

直接使用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路径下

  

 

分类:

技术点:

相关文章:

  • 2022-02-09
  • 2022-02-09
  • 2022-02-09
  • 2021-10-16
  • 2021-12-05
  • 2021-12-15
  • 2022-12-23
  • 2021-12-15
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案