一直使用python处理excel文件,php项目中使用maatwebsite/excel来处理excel文件,发现特别强大,记录使用过程。
由于新版3.1改版较大,改成使用2.1,后面根据须要会调整php
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)
composer require "maatwebsite/excel": "~2.1.0"
app/config/app.configpython
config/app.php //Package Service Providers... 'providers' => [ Maatwebsite\Excel\ExcelServiceProvider::class, ] 'aliases' => [ 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ]
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Excel::load('file.xls', function($reader) { // reader methods });
注意文件能够是存储的文件,或者经过客户端传递的文件,经过客户端传递的文件须要完成客户端传递文件的逻辑和基本的文件检测以下给个示例:web
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' => '']; }
Excel::load('local_store.xls', function($reader) { })->get(); //或者 Excel::load('local_store.xls', function($reader) { // 获取全部的结果集 $results = $reader->get(); //或者使用all //$results = $reader->all(); });