laravel处理excel文件第三方包 maatwebsite/excel的使用

一直使用python处理excel文件,php项目中使用maatwebsite/excel来处理excel文件,发现特别强大,记录使用过程。
因为新版3.1改版较大,改为使用2.1,后面根据需要会调整

1. 安装第三方包需要一些其他的包,需求如下:
PHP version >= 5.3.7
Laravel >= 4.1
PHPOffice PHPExcel >= 1.8.0 (included by composer.json)
PHP extension php_zip enabled (required if you need PHPExcel to handle .xlsx .ods or .gnumeric files)
PHP extension php_xml enabled
PHP extension php_gd2 enabled (optional, but required for exact column width autocalculation)
2. 安装第三方包
composer require "maatwebsite/excel": "~2.1.0"
3. 注入facade到配置文件

app/config/app.config

config/app.php
//Package Service Providers...
'providers' => [
    Maatwebsite\Excel\ExcelServiceProvider::class,
]
'aliases' => [
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
4. 发布配置文件
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
5.载入文件
Excel::load('file.xls', function($reader) {

    // reader methods

});

注意文件可以是存储的文件,或者通过客户端传递的文件,通过客户端传递的文件需要完成客户端传递文件的逻辑和基本的文件检测如下给个示例:

function checkFileUploadTrue(){
    // UPLOAD_ERR_OK => '文件上传成功。'
            // 下面的错误对应的整数位1-》1
    $error = [
        UPLOAD_ERR_INI_SIZE => '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。',//1
        UPLOAD_ERR_FORM_SIZE => '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。',//2
        UPLOAD_ERR_PARTIAL => '文件只有部分被上传。',//3
        UPLOAD_ERR_NO_FILE => '没有文件被上传。',//4
        UPLOAD_ERR_NO_TMP_DIR => '找不到临时文件夹。',//6
        UPLOAD_ERR_CANT_WRITE => '文件写入失败。'//7
    ];
    // 检测error是否为0,其他的任务不成功
    if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        return ['flag'=> False,'msg' => $error[$_FILES['file']['error']]];
    }
    // 检测是否为上传文件
    if (!is_uploaded_file($_FILES["file"]["tmp_name"])) {
       return ['flag' => False, 'msg' => '不是上传的文件!'];
    }
    // 检测是否为约定的文件类型
    $file_type = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel'];
    if (!in_array($_FILES['file']['type'],$file_type)) {
        return ['flag' => False, 'msg' => '只能上传excel类型文件'];
    }
    // 目录
    $storage_file_dir = '/data/file/tmp/';
    //转存文件
    $tmp_filename = $_FILES['file']['tmp_name'];
    $dest_filename = $storage_file_dir.$_FILES['file']['name'];
    if(!move_uploaded_file($tmp_filename,$dest_filename)){
        return ['flag' => False, 'msg' => '文件转存失败,确认之后再转存!'];
    }
    return ['flag'=> True,'msg' => ''];
}
6.文件读取内容,可以使用两种方式
Excel::load('local_store.xls', function($reader) {

})->get();

//或者

Excel::load('local_store.xls', function($reader) {

    // 获取所有的结果集
    $results = $reader->get();

    //或者使用all
    //$results = $reader->all();

});

猜你喜欢

转载自www.cnblogs.com/linnenn/p/11290534.html