一直使用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();
});
