• PHPWord使用方法


    官方文档  github地址

    一、安装

    直接使用composer安装,链接地址

    composer require phpoffice/phpword
    

      

    二、简单使用

    require_once 'PhpOffice/PhpWord/PhpWord.php'; // 包含头文件
    use PhpOfficePhpWordAutoloader;
    use PhpOfficePhpWordSettings;
    use PhpOfficePhpWordIOFactory;
     
    require_once __DIR__ . '/PhpOffice/PhpWord/Autoloader.php';
    Autoloader::register();
    Settings::loadConfig();
     
    // Create a new PHPWord Object
    $PHPWord = new PhpOfficePhpWordPhpWord();
    $PHPWordHelper= new PhpOfficePhpWordSharedFont();
     
    $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路径下
    

      

  • 相关阅读:
    一个从excel导入数据错位问题
    Chrome F12 温故而知新 :因为重定向导致清空Network信息
    export / import 温故而知新
    Chrome Debugger 温故而知新:上下文环境
    微信导出表情包教程
    Oracle中判断字段是否为数字
    获取GridView中RowCommand的当前索引行
    Oracle SQL常用内置系统函数总结
    使用Task代替ThreadPool和Thread
    Visual Studio 使用及调试必知必会
  • 原文地址:https://www.cnblogs.com/shifu204/p/9540685.html
Copyright © 2020-2023  润新知