laravel 的EXCEL读写 maatwebsite/excel

程序中经常要用到EXCEL表格操作。 maatwebsite/excel是一个不错的程序包。

项目地址

https://github.com/Maatwebsite/Laravel-Excel

官方文档:

http://www.maatwebsite.nl/laravel-excel/docs/getting-started#installation

安装方法。

1. 项目的composer.json 中添加

"maatwebsite/excel": "~2.1.0"     如果是 Laravel 4  则添加    
"maatwebsite/excel": "~1.3"      (确信版本正确,勿入坑,以下都是laravel 5步骤)

2, 执行 composer update maatwebsite/excel

Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Removing maatwebsite/excel (v1.3.7)
  - Installing maatwebsite/excel (v2.1.2)
    Downloading: 100%

3,编辑 app/config/app.php

在代码中分别加入

然后添加Maatwebsite\Excel\ExcelServiceProvider::class,,到config/app.php中的providers数组中

添加'Excel' => 'Maatwebsite\Excel\Facades\Excel',到aliases数组中

4,执行命令 生成配置文件

 php artisan vendor:publish

6, 开始用了。

在项目中 先use

 use Excel;

导出excel

$localstock=LocalStock::with('classify','version')->Orderby('id','desc')->get()->toArray();
        Excel::create('本地库存-'.date('Y_m_d H_i_s'), function($excel) use($localstock){
            $excel->sheet('Excel sheet', function($sheet) use($localstock) {
                $sheet->prependRow(1, ['ID','仪器分类','仪器型号', '单价', '库存', '备注']);
                $sheet->setSize([
                    'A1' => ['width'=>30,'height'=> 20],
                    'B1' => ['width'=>30,'height'=> 20],
                    'C1' => ['width'=>30,'height'=> 20],
                    'D1' => ['width'=>30,'height'=> 20],
                    'E1' => ['width'=>30,'height'=> 20],
                    'F1' => ['width'=>30,'height'=> 20],
                ]);
                for($i=2; $i<count($localstock)+2; $i++){
                    $sheet->row($i, [$localstock[$i-2]['classify']['title'],$localstock[$i-2]['version']['title'],$localstock[$i-2]['price'],$localstock[$i-2]['num'],$localstock[$i-2]['remark']]);
                }
            });
        })->export('xls');

注意:在导出excel之前不要有任何的php输出,如echo、print等,不然导出的excel全都是乱码。

导入Excel

$res = $this->Importexcel($path);  

var_dump($res);  



public function Importexcel($files){  

    $res = [];  
    Excel::load($files, function($reader) use( &$res ) {  
        $reader = $reader->getSheet(0);  
        $res = $reader->toArray();  
    });  

    return $res;  
}  
HTTPROOT | 自学PHP | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 石头哥 |微信小程序 |木讯 |备案
Copyright © 1998 - 2016 HTTPROOT.COM. All Rights Reserved httproot.com 版权所有