Laravel9 Excel导入 和 Word导入
Excel导入类:
<?php namespace App\Utils; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Maatwebsite\Excel\Facades\Excel; class ExcelImporter { public function import(UploadedFile $file) { $path = Storage::putFile('uploads', $file); $rows = Excel::toArray([], $path); Storage::delete($path); return $rows; } }
Word导入类:
<?php namespace App\Utils; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use PhpOffice\PhpWord\PhpWord; class WordImporter { public function import(UploadedFile $file) { $path = Storage::putFile('uploads', $file); $phpWord = PhpWord::load($path); $text = $phpWord->getText(); Storage::delete($path); return $text; } }
这里使用了Maatwebsite\Excel和PhpOffice\PhpWord两个第三方包来实现Excel和Word的导入。在ExcelImporter类中,我们将上传的文件保存到存储中,并使用Excel::toArray()方法将Excel文件转换为数组,然后删除上传的文件。在WordImporter类中,我们将上传的文件保存到存储中,并使用PhpWord::load()方法将Word文件加载到PhpWord对象中,然后使用PhpWord->getText()方法获取文本内容,并删除上传的文件。