• 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");
  • 相关阅读:
    对websoceket进行压力测试(一)
    学习springboot的一个网站
    重装mysql数据库
    websocket扫盲:基础知识(二)
    json-lib 之jsonConfig详细使用
    hibernate的like用法(用占位符解决)
    【转载】hibernate查询参数绑定
    Struts2 Anotation action
    PLSQL怎样导出oracle表结构
    从命令行启动oracle服务
  • 原文地址:https://www.cnblogs.com/xuey/p/16021698.html
Copyright © 2020-2023  润新知