PHPWord

作者admin

8月 8, 2024

PHPWord 是一个开源库,用于在 PHP 中创建、读取和写入 Microsoft Word 文件。它支持 .docx、.odt 和其他一些格式。PHPWord 提供了一个简单的 API,可以方便地操作 Word 文档。

创建一个新文档

require ‘vendor/autoload.php’;

use PhpOffice\PhpWord\PhpWord;

// 创建一个新的PHPWord对象
$phpWord = new PhpWord();

// 添加一个新页面
$section = $phpWord->addSection();

// 添加文本
$section->addText(‘Hello World!’);

// 保存文档
$phpWord->save(‘hello_world.docx’, ‘Word2007’);

加载并编辑文档

require ‘vendor/autoload.php’;

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;

$templateProcessor = new TemplateProcessor(‘path/to/your/template.docx’);

// 替换变量
$templateProcessor->setValue(‘一次年’, ‘2024’);
$templateProcessor->setValue(‘首付款’, ‘5000’);

// 保存编辑后的文档到临时文件
$tempFilePath = tempnam(sys_get_temp_dir(), ‘phpword’);
$templateProcessor->saveAs($tempFilePath);

// 将文档内容输出到浏览器
header(‘Content-Description: File Transfer’);
header(‘Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document’);
header(‘Content-Disposition: attachment; filename=”edited_document.docx”‘);
header(‘Content-Transfer-Encoding: binary’);
header(‘Expires: 0’);
header(‘Cache-Control: must-revalidate, post-check=0, pre-check=0’);
header(‘Pragma: public’);
header(‘Content-Length: ‘ . filesize($tempFilePath));
readfile($tempFilePath);

作者 admin

百度广告效果展示