在 Laravel 中处理 Word 文档的详细实现方案如下:
- 完整安装与配置
composer require phpoffice/phpword
- 核心功能实现
2.1 文档生成(带样式)
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Converter;
use PhpOffice\PhpWord\Style\Font;
$phpWord = new PhpWord();
$section = $phpWord->addSection();
// 添加标题(带样式)
$fontStyle = ['name'=>'Arial', 'size'=>16, 'color'=>'006699'];
$phpWord->addTitleStyle(1, $fontStyle);
$section->addTitle('文档标题', 1);
// 添加表格
$table = $section->addTable();
$table->addRow();
$table->addCell(2000)->addText('ID');
$table->addCell(4000)->addText('名称');
2.2 模板处理(实际开发中最常用)
// 准备模板文件 template.docx 包含变量如 ${name}
$template = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
$template->setValue('name', '张三');
$template->setValue('date', date('Y-m-d'));
// 克隆表格行
$template->cloneRow('item', 3); // 克隆3行
$template->setValue('item#1', '值1'); // 第一行
$template->setValue('item#2', '值2'); // 第二行
$template->saveAs('output.docx');
- 文件上传处理
// 在控制器中
public function upload(Request $request) {
$file = $request->file('word_file');
$path = $file->store('word_templates');
// 处理上传的Word
$phpWord = IOFactory::load(storage_path('app/'.$path));
// ...处理逻辑
}
- 与Eloquent集成示例
public function generateReport($userId) {
$user = User::find($userId);
$template = new TemplateProcessor('user_report.docx');
$template->setValue('username', $user->name);
$template->setValue('email', $user->email);
return response()->download($template->saveAs('temp_report.docx'))->deleteFileAfterSend(true);
}